forked from 61bcdefg/Hikari-LLVM15-Core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FunctionCallObfuscate.cpp
317 lines (311 loc) · 12.4 KB
/
FunctionCallObfuscate.cpp
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
// For open-source license, please refer to
// [License](https://github.com/HikariObfuscator/Hikari/wiki/License).
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Obfuscation/FunctionCallObfuscate.h"
#include "json.hpp"
#if LLVM_VERSION_MAJOR >= 17
#include "llvm/ADT/SmallString.h"
#include "llvm/TargetParser/Triple.h"
#else
#include "llvm/ADT/Triple.h"
#endif
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Obfuscation/Utils.h"
#include "llvm/Transforms/Obfuscation/compat/CallSite.h"
#include <fstream>
#include <set>
using namespace llvm;
static const int DARWIN_FLAG = 0x2 | 0x8;
static const int ANDROID64_FLAG = 0x00002 | 0x100;
static const int ANDROID32_FLAG = 0x0000 | 0x2;
static cl::opt<uint64_t>
dlopen_flag("fco_flag",
cl::desc("The value of RTLD_DEFAULT on your platform"),
cl::value_desc("value"), cl::init(-1), cl::Optional);
static cl::opt<std::string>
SymbolConfigPath("fcoconfig",
cl::desc("FunctionCallObfuscate Configuration Path"),
cl::value_desc("filename"), cl::init("+-x/"));
namespace llvm {
struct FunctionCallObfuscate : public FunctionPass {
static char ID;
nlohmann::json Configuration;
bool flag;
bool initialized;
bool opaquepointers;
Triple triple;
FunctionCallObfuscate() : FunctionPass(ID) {
this->flag = true;
this->initialized = false;
}
FunctionCallObfuscate(bool flag) : FunctionPass(ID) {
this->flag = flag;
this->initialized = false;
}
StringRef getPassName() const override { return "FunctionCallObfuscate"; }
bool initialize(Module &M) {
// Basic Defs
if (SymbolConfigPath == "+-x/") {
SmallString<32> Path;
if (sys::path::home_directory(Path)) { // Stolen from LineEditor.cpp
sys::path::append(Path, "Hikari", "SymbolConfig.json");
SymbolConfigPath = Path.c_str();
}
}
std::ifstream infile(SymbolConfigPath);
if (infile.good()) {
errs() << "Loading Symbol Configuration From:" << SymbolConfigPath
<< "\n";
infile >> this->Configuration;
} else {
errs() << "Failed To Load Symbol Configuration From:" << SymbolConfigPath
<< "\n";
}
this->triple = Triple(M.getTargetTriple());
if (triple.getVendor() == Triple::VendorType::Apple) {
Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
// Generic ObjC Runtime Declarations
FunctionType *IMPType =
FunctionType::get(Int8PtrTy, {Int8PtrTy, Int8PtrTy}, true);
PointerType *IMPPointerType = PointerType::get(IMPType, 0);
FunctionType *class_replaceMethod_type = FunctionType::get(
IMPPointerType, {Int8PtrTy, Int8PtrTy, IMPPointerType, Int8PtrTy},
false);
M.getOrInsertFunction("class_replaceMethod", class_replaceMethod_type);
FunctionType *sel_registerName_type =
FunctionType::get(Int8PtrTy, {Int8PtrTy}, false);
M.getOrInsertFunction("sel_registerName", sel_registerName_type);
FunctionType *objc_getClass_type =
FunctionType::get(Int8PtrTy, {Int8PtrTy}, false);
M.getOrInsertFunction("objc_getClass", objc_getClass_type);
M.getOrInsertFunction("objc_getMetaClass", objc_getClass_type);
FunctionType *class_getName_Type =
FunctionType::get(Int8PtrTy, {Int8PtrTy}, false);
M.getOrInsertFunction("class_getName", class_getName_Type);
FunctionType *objc_getMetaClass_Type =
FunctionType::get(Int8PtrTy, {Int8PtrTy}, false);
M.getOrInsertFunction("objc_getMetaClass", objc_getMetaClass_Type);
}
this->initialized = true;
#if LLVM_VERSION_MAJOR >= 17
this->opaquepointers = true;
#else
this->opaquepointers = !M.getContext().supportsTypedPointers();
#endif
return true;
}
bool OnlyUsedByCompilerUsed(GlobalVariable *GV) {
if (GV->getNumUses() == 1) {
User *U = GV->user_back();
if (U->getNumUses() == 1) {
if (GlobalVariable *GVU = dyn_cast<GlobalVariable>(U->user_back())) {
if (GVU->getName() == "llvm.compiler.used")
return true;
}
}
}
return false;
}
void HandleObjC(Function *F) {
SmallPtrSet<GlobalVariable *, 8> objcclassgv, objcselgv, selnamegv;
for (Instruction &I : instructions(F))
for (Value *Op : I.operands())
if (GlobalVariable *G =
dyn_cast<GlobalVariable>(Op->stripPointerCasts())) {
if (!G->hasName() || !G->hasInitializer() ||
!G->getSection().contains("objc"))
continue;
if (G->getName().startswith("OBJC_CLASSLIST_REFERENCES"))
objcclassgv.insert(G);
else if (G->getName().startswith("OBJC_SELECTOR_REFERENCES"))
objcselgv.insert(G);
}
Module *M = F->getParent();
SmallVector<Instruction *, 8> toErase;
for (GlobalVariable *GV : objcclassgv) {
// Iterate all CLASSREF uses and replace with objc_getClass() call
// Strings are encrypted in other passes
std::string className = GV->getInitializer()->getName().str();
className.replace(className.find("OBJC_CLASS_$_"),
strlen("OBJC_CLASS_$_"), "");
for (User *U : GV->users())
if (Instruction *I = dyn_cast<Instruction>(U)) {
IRBuilder<> builder(I);
Function *objc_getClass_Func =
cast<Function>(M->getFunction("objc_getClass"));
Value *newClassName =
builder.CreateGlobalStringPtr(StringRef(className));
CallInst *CI = builder.CreateCall(objc_getClass_Func, {newClassName});
// We need to bitcast it back to avoid IRVerifier
Value *BCI = builder.CreateBitCast(CI, I->getType());
I->replaceAllUsesWith(BCI);
toErase.emplace_back(I); // We cannot erase it directly or we will
// have problems releasing the IRBuilder.
}
}
for (GlobalVariable *GV : objcselgv) {
// Selector Convert
GlobalVariable *selgv = dyn_cast<GlobalVariable>(
opaquepointers
? GV->getInitializer()
: cast<ConstantExpr>(GV->getInitializer())->getOperand(0));
selnamegv.insert(selgv);
ConstantDataArray *CDA =
dyn_cast<ConstantDataArray>(selgv->getInitializer());
StringRef SELName = CDA->getAsString(); // This is REAL Selector Name
for (User *U : GV->users())
if (Instruction *I = dyn_cast<Instruction>(U)) {
IRBuilder<> builder(I);
Function *sel_registerName_Func =
cast<Function>(M->getFunction("sel_registerName"));
Value *newGlobalSELName = builder.CreateGlobalStringPtr(SELName);
CallInst *CI =
builder.CreateCall(sel_registerName_Func, {newGlobalSELName});
// We need to bitcast it back to avoid IRVerifier
Value *BCI = builder.CreateBitCast(CI, I->getType());
I->replaceAllUsesWith(BCI);
toErase.emplace_back(I); // We cannot erase it directly or we will
// have problems releasing the IRBuilder.
}
}
for (Instruction *I : toErase)
I->eraseFromParent();
for (GlobalVariable *GV : objcclassgv) {
GV->removeDeadConstantUsers();
if (OnlyUsedByCompilerUsed(GV)) {
GV->replaceAllUsesWith(Constant::getNullValue(GV->getType()));
}
if (GV->getNumUses() == 0) {
GV->dropAllReferences();
GV->eraseFromParent();
continue;
}
}
for (GlobalVariable *GV : objcselgv) {
GV->removeDeadConstantUsers();
if (OnlyUsedByCompilerUsed(GV)) {
GV->replaceAllUsesWith(Constant::getNullValue(GV->getType()));
}
if (GV->getNumUses() == 0) {
GV->dropAllReferences();
GV->eraseFromParent();
}
}
for (GlobalVariable *GV : selnamegv) {
GV->removeDeadConstantUsers();
if (OnlyUsedByCompilerUsed(GV)) {
GV->replaceAllUsesWith(Constant::getNullValue(GV->getType()));
}
if (GV->getNumUses() == 0) {
GV->dropAllReferences();
GV->eraseFromParent();
}
}
}
bool runOnFunction(Function &F) override {
// Construct Function Prototypes
if (!toObfuscate(flag, &F, "fco"))
return false;
errs() << "Running FunctionCallObfuscate On " << F.getName() << "\n";
Module *M = F.getParent();
if (!this->initialized)
initialize(*M);
if (!triple.isAndroid() && !triple.isOSDarwin()) {
errs() << "Unsupported Target Triple: " << M->getTargetTriple() << "\n";
return false;
}
FixFunctionConstantExpr(&F);
HandleObjC(&F);
Type *Int32Ty = Type::getInt32Ty(M->getContext());
Type *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
// ObjC Runtime Declarations
FunctionType *dlopen_type = FunctionType::get(
Int8PtrTy, {Int8PtrTy, Int32Ty},
false); // int has a length of 32 on both 32/64bit platform
FunctionType *dlsym_type =
FunctionType::get(Int8PtrTy, {Int8PtrTy, Int8PtrTy}, false);
Function *dlopen_decl = cast<Function>(
M->getOrInsertFunction("dlopen", dlopen_type).getCallee());
Function *dlsym_decl =
cast<Function>(M->getOrInsertFunction("dlsym", dlsym_type).getCallee());
// Begin Iteration
for (BasicBlock &BB : F) {
for (Instruction &Inst : BB) {
if (isa<CallInst>(&Inst) || isa<InvokeInst>(&Inst)) {
CallSite CS(&Inst);
Function *calledFunction = CS.getCalledFunction();
if (!calledFunction) {
/*
Note:
For Indirect Calls:
CalledFunction is NULL and calledValue is usually a bitcasted
function pointer. We'll need to strip out the hiccups and obtain
the called Function* from there
*/
calledFunction =
dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
}
// Simple Extracting Failed
// Use our own implementation
if (!calledFunction)
continue;
// It's only safe to restrict our modification to external symbols
// Otherwise stripped binary will crash
if (!calledFunction->empty() ||
calledFunction->getName().equals("dlsym") ||
calledFunction->getName().equals("dlopen") ||
calledFunction->isIntrinsic())
continue;
if (this->Configuration.find(calledFunction->getName().str()) !=
this->Configuration.end()) {
std::string sname =
this->Configuration[calledFunction->getName().str()]
.get<std::string>();
StringRef calledFunctionName = StringRef(sname);
BasicBlock *EntryBlock = CS->getParent();
if (triple.isOSDarwin()) {
dlopen_flag = DARWIN_FLAG;
} else if (triple.isAndroid()) {
if (triple.isArch64Bit())
dlopen_flag = ANDROID64_FLAG;
else
dlopen_flag = ANDROID32_FLAG;
} else {
errs() << "[FunctionCallObfuscate] Unsupported Target Triple:"
<< M->getTargetTriple() << "\n";
errs() << "[FunctionCallObfuscate] Applying Default Signature:"
<< dlopen_flag << "\n";
}
IRBuilder<> IRB(EntryBlock, EntryBlock->getFirstInsertionPt());
Value *Handle = IRB.CreateCall(
dlopen_decl, {Constant::getNullValue(Int8PtrTy),
ConstantInt::get(Int32Ty, dlopen_flag)});
// Create dlsym call
Value *fp = IRB.CreateCall(
dlsym_decl,
{Handle, IRB.CreateGlobalStringPtr(calledFunctionName)});
Value *bitCastedFunction =
IRB.CreateBitCast(fp, CS.getCalledValue()->getType());
CS.setCalledFunction(bitCastedFunction);
}
}
}
}
return true;
}
};
FunctionPass *createFunctionCallObfuscatePass(bool flag) {
return new FunctionCallObfuscate(flag);
}
} // namespace llvm
char FunctionCallObfuscate::ID = 0;
INITIALIZE_PASS(FunctionCallObfuscate, "fcoobf",
"Enable Function CallSite Obfuscation.", false, false)