This repository has been archived by the owner on Jul 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
FunctionCallObfuscate.cpp
319 lines (318 loc) · 13.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
318
319
// For open-source license, please refer to [License](https://github.com/HikariObfuscator/Hikari/wiki/License).
//===----------------------------------------------------------------------===//
#include "json.hpp"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Obfuscation/Obfuscation.h"
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
using namespace llvm;
using namespace std;
using json = nlohmann::json;
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<string>
SymbolConfigPath("fcoconfig",
cl::desc("FunctionCallObfuscate Configuration Path"),
cl::value_desc("filename"), cl::init("+-x/"));
namespace llvm {
struct FunctionCallObfuscate : public FunctionPass {
static char ID;
json Configuration;
bool flag;
FunctionCallObfuscate() : FunctionPass(ID) { this->flag = true; }
FunctionCallObfuscate(bool flag) : FunctionPass(ID) { this->flag = flag; }
StringRef getPassName() const override {
return StringRef("FunctionCallObfuscate");
}
virtual bool doInitialization(Module &M) override {
// 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.str();
}
}
ifstream infile(SymbolConfigPath);
if (infile.good()) {
errs() << "Loading Symbol Configuration From:" << SymbolConfigPath
<< "\n";
infile >> this->Configuration;
} else {
errs() << "Failed To Loading Symbol Configuration From:"
<< SymbolConfigPath << "\n";
}
Triple tri(M.getTargetTriple());
if (tri.getVendor() != Triple::VendorType::Apple) {
return false;
}
Type *Int64Ty = Type::getInt64Ty(M.getContext());
Type *Int32Ty = Type::getInt32Ty(M.getContext());
Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
Type *Int8Ty = Type::getInt8Ty(M.getContext());
// Generic ObjC Runtime Declarations
FunctionType *IMPType =
FunctionType::get(Int8PtrTy, {Int8PtrTy, Int8PtrTy}, true);
PointerType *IMPPointerType = PointerType::get(IMPType, 0);
vector<Type *> classReplaceMethodTypeArgs;
classReplaceMethodTypeArgs.push_back(Int8PtrTy);
classReplaceMethodTypeArgs.push_back(Int8PtrTy);
classReplaceMethodTypeArgs.push_back(IMPPointerType);
classReplaceMethodTypeArgs.push_back(Int8PtrTy);
FunctionType *class_replaceMethod_type =
FunctionType::get(IMPPointerType, classReplaceMethodTypeArgs, 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);
StructType *objc_property_attribute_t_type = reinterpret_cast<StructType *>(
M.getTypeByName("struct.objc_property_attribute_t"));
if (objc_property_attribute_t_type == NULL) {
vector<Type *> types;
types.push_back(Int8PtrTy);
types.push_back(Int8PtrTy);
objc_property_attribute_t_type = StructType::create(
ArrayRef<Type *>(types), "struct.objc_property_attribute_t");
M.getOrInsertGlobal("struct.objc_property_attribute_t",
objc_property_attribute_t_type);
}
vector<Type *> allocaClsTypeVector;
vector<Type *> addIvarTypeVector;
vector<Type *> addPropTypeVector;
allocaClsTypeVector.push_back(Int8PtrTy);
allocaClsTypeVector.push_back(Int8PtrTy);
addIvarTypeVector.push_back(Int8PtrTy);
addIvarTypeVector.push_back(Int8PtrTy);
addPropTypeVector.push_back(Int8PtrTy);
addPropTypeVector.push_back(Int8PtrTy);
addPropTypeVector.push_back(objc_property_attribute_t_type->getPointerTo());
if (tri.isArch64Bit()) {
// We are 64Bit Device
allocaClsTypeVector.push_back(Int64Ty);
addIvarTypeVector.push_back(Int64Ty);
addPropTypeVector.push_back(Int64Ty);
} else {
// Not 64Bit.However we are still on apple platform.So We are
// ARMV7/ARMV7S/i386
// PowerPC is ignored, feel free to open a PR if you want to
allocaClsTypeVector.push_back(Int32Ty);
addIvarTypeVector.push_back(Int32Ty);
addPropTypeVector.push_back(Int32Ty);
}
addIvarTypeVector.push_back(Int8Ty);
addIvarTypeVector.push_back(Int8PtrTy);
// Types Collected. Now Inject Functions
FunctionType *addIvarType =
FunctionType::get(Int8Ty, ArrayRef<Type *>(addIvarTypeVector), false);
M.getOrInsertFunction("class_addIvar", addIvarType);
FunctionType *addPropType =
FunctionType::get(Int8Ty, ArrayRef<Type *>(addPropTypeVector), false);
M.getOrInsertFunction("class_addProperty", addPropType);
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);
return true;
}
void HandleObjC(Module &M) {
// Iterate all CLASSREF uses and replace with objc_getClass() call
// Strings are encrypted in other passes
for (auto G = M.global_begin(); G != M.global_end(); G++) {
GlobalVariable &GV = *G;
if (GV.getName().str().find("OBJC_CLASSLIST_REFERENCES") == 0) {
if (GV.hasInitializer()) {
string className = GV.getInitializer()->getName();
className.replace(className.find("OBJC_CLASS_$_"),
strlen("OBJC_CLASS_$_"), "");
for (auto U = GV.user_begin(); U != GV.user_end(); U++) {
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);
I->eraseFromParent();
}
}
GV.removeDeadConstantUsers();
if (GV.getNumUses() == 0) {
GV.dropAllReferences();
GV.eraseFromParent();
}
}
}
// Selector Convert
else if (GV.getName().str().find("OBJC_SELECTOR_REFERENCES") == 0) {
if (GV.hasInitializer()) {
ConstantExpr *CE = dyn_cast<ConstantExpr>(GV.getInitializer());
Constant *C = CE->getOperand(0);
GlobalVariable *SELNameGV = dyn_cast<GlobalVariable>(C);
ConstantDataArray *CDA =
dyn_cast<ConstantDataArray>(SELNameGV->getInitializer());
StringRef SELName = CDA->getAsString(); // This is REAL Selector Name
for (auto U = GV.user_begin(); U != GV.user_end(); U++) {
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);
I->eraseFromParent();
}
}
GV.removeDeadConstantUsers();
if (GV.getNumUses() == 0) {
GV.dropAllReferences();
GV.eraseFromParent();
}
}
}
}
}
virtual bool runOnFunction(Function &F) override {
// Construct Function Prototypes
if (toObfuscate(flag, &F, "fco") == false) {
return false;
}
Triple Tri(F.getParent()->getTargetTriple());
if (!Tri.isAndroid() && !Tri.isOSDarwin()) {
errs() << "Unsupported Target Triple:"<< F.getParent()->getTargetTriple() << "\n";
return false;
}
errs() << "Running FunctionCallObfuscate On " << F.getName() << "\n";
Module *M = F.getParent();
FixFunctionConstantExpr(&F);
HandleObjC(*M);
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));
Function *dlsym_decl =
cast<Function>(M->getOrInsertFunction("dlsym", dlsym_type));
// Begin Iteration
for (BasicBlock &BB : F) {
for (auto I = BB.getFirstInsertionPt(), end = BB.end(); I != end; ++I) {
Instruction &Inst = *I;
if (isa<CallInst>(&Inst) || isa<InvokeInst>(&Inst)) {
CallSite CS(&Inst);
Function *calledFunction = CS.getCalledFunction();
if (calledFunction == NULL) {
/*
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 == NULL) {
DEBUG_WITH_TYPE(
"opt", errs()
<< "Failed To Extract Function From Indirect Call: "
<< *CS.getCalledValue() << "\n");
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;
}
// errs()<<"Searching For:"<<calledFunction->getName()<<" In
// Configuration\n";
if (this->Configuration.find(calledFunction->getName().str()) !=
this->Configuration.end()) {
string sname = this->Configuration[calledFunction->getName().str()]
.get<string>();
StringRef calledFunctionName = StringRef(sname);
BasicBlock *EntryBlock = CS->getParent();
IRBuilder<> IRB(EntryBlock, EntryBlock->getFirstInsertionPt());
vector<Value *> dlopenargs;
dlopenargs.push_back(Constant::getNullValue(Int8PtrTy));
if (Tri.isOSDarwin()) {
dlopen_flag=DARWIN_FLAG;
} else if (Tri.isAndroid()) {
if (Tri.isArch64Bit()) {
dlopen_flag=ANDROID64_FLAG;
} else {
dlopen_flag=ANDROID32_FLAG;
}
} else {
errs() << "[FunctionCallObfuscate]Unsupported Target Triple:"
<< F.getParent()->getTargetTriple() << "\n";
errs()<<"[FunctionCallObfuscate]Applying Default Signature:"<<dlopen_flag<<"\n";
}
dlopenargs.push_back(ConstantInt::get(Int32Ty, dlopen_flag));
Value *Handle =
IRB.CreateCall(dlopen_decl, ArrayRef<Value *>(dlopenargs));
// Create dlsym call
vector<Value *> args;
args.push_back(Handle);
args.push_back(IRB.CreateGlobalStringPtr(calledFunctionName));
Value *fp = IRB.CreateCall(dlsym_decl, ArrayRef<Value *>(args));
Value *bitCastedFunction =
IRB.CreateBitCast(fp, CS.getCalledValue()->getType());
CS.setCalledFunction(bitCastedFunction);
}
}
}
}
return true;
}
};
FunctionPass *createFunctionCallObfuscatePass() {
return new FunctionCallObfuscate();
}
FunctionPass *createFunctionCallObfuscatePass(bool flag) {
return new FunctionCallObfuscate(flag);
}
} // namespace llvm
char FunctionCallObfuscate::ID = 0;
INITIALIZE_PASS(FunctionCallObfuscate, "fcoobf",
"Enable Function CallSite Obfuscation.", true, true)