-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathStringObfuscation.cpp
More file actions
251 lines (209 loc) · 8.4 KB
/
StringObfuscation.cpp
File metadata and controls
251 lines (209 loc) · 8.4 KB
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
#include "StringObfuscation.h"
#include "string/decode.h"
#include "utils/Utils.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassBuilder.h"
#if LLVM_VERSION_MAJOR >= 22
#include "llvm/Plugins/PassPlugin.h"
#else
#include "llvm/Passes/PassPlugin.h"
#endif
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <llvm/IRReader/IRReader.h>
#include <llvm/Transforms/Utils/ModuleUtils.h>
#include "utils/CryptoUtils.h"
static const unsigned int RandomNameMinSize = 5;
static const unsigned int RandomMaxNameSize = 15;
static const char ALPHANUM[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
using namespace llvm;
namespace llvm {
ConstantDataArray *StringObfuscatorPass::encodeStringDataArray(LLVMContext &ctx,
const char *str,
size_t size,
uint8_t key) {
if (this->maxSize != 0 && size > this->maxSize)
return nullptr;
// Encode the data
char *encodedStr = (char *)malloc(size);
for (unsigned int i = 0; i < size; i++) {
encodedStr[i] = str[i] ^ key;
}
// Update the value
auto encodedRef = StringRef(encodedStr, size);
// Return a new ConstantDataArray
return static_cast<ConstantDataArray *>(
ConstantDataArray::getString(ctx, encodedRef, false));
}
void StringObfuscatorPass::encodeGlobalString(LLVMContext &ctx,
GlobalVariable *gv,
ConstantDataArray *array) {
StringRef ref = array->getAsString();
const char *str = ref.data();
const unsigned int size = ref.size();
uint8_t key = cryptoutils->get_uint8_t();
auto encodedArray = encodeStringDataArray(ctx, str, size, key);
if (encodedArray != nullptr) {
gv->setInitializer(encodedArray);
gv->setConstant(false);
this->globalStrings.push_back(
GlobalStringVariable(gv, size, 0, false, key));
}
}
void StringObfuscatorPass::encodeStructString(LLVMContext &ctx,
GlobalVariable *gv,
ConstantStruct *cs,
ConstantDataArray *array,
unsigned int index) {
StringRef ref = array->getAsString();
const char *str = ref.data();
const unsigned int size = ref.size();
uint8_t key = llvm::cryptoutils->get_uint8_t();
auto encodedArray = encodeStringDataArray(ctx, str, size, key);
if (encodedArray != nullptr) {
cs->setOperand(index, encodedArray);
gv->setConstant(false);
this->globalStrings.push_back(
GlobalStringVariable(gv, size, index, true, key));
}
}
StringObfuscatorPass::StringObfuscatorPass(size_t maxSize) : maxSize{maxSize} {}
bool StringObfuscatorPass::encodeAllStrings(Module &M) {
auto &ctx = M.getContext();
// For each global variable
for (GlobalVariable &gv : M.globals()) {
if (!gv.isConstant() // constant
|| !gv.hasInitializer() // unitialized
|| gv.hasExternalLinkage() // external
|| gv.getAlign().valueOrOne().value() != 1 // align == 1
|| gv.getSection() == "llvm.metadata") { // Intrinsic Global Variables
//|| gv.getSection().find("__objc_methname") != string::npos) { // TODO :
// is this necessary ?
continue;
}
// Get the variable value
Constant *initializer = gv.getInitializer();
// Encode the value and update the variable
if (isa<ConstantDataArray>(initializer)) { // Global variable
auto array = cast<ConstantDataArray>(initializer);
if (array->isString()) {
encodeGlobalString(ctx, &gv, array);
}
} else if (isa<ConstantStruct>(initializer)) { // Variable in a struct
auto cs = cast<ConstantStruct>(initializer);
for (unsigned int i = 0; i < initializer->getNumOperands(); i++) {
auto operand = cs->getOperand(i);
if (isa<ConstantDataArray>(operand)) {
auto array = cast<ConstantDataArray>(operand);
if (array->isString()) {
encodeStructString(ctx, &gv, cs, array, i);
}
}
}
}
}
return !this->globalStrings.empty();
}
std::string StringObfuscatorPass::generateRandomName() {
std::string name = "";
auto charsetSize = strlen(ALPHANUM) - 1;
auto size =
MIN(cryptoutils->get_uint8_t() + RandomNameMinSize, RandomMaxNameSize);
for (unsigned int i = 0; i < size; i++) {
auto index = cryptoutils->get_range(charsetSize);
name += ALPHANUM[index];
}
return name;
}
Function *StringObfuscatorPass::addDecodeFunction(Module &M) {
auto &ctx = M.getContext();
// Parse the bitcode from the header (creates a new module which contains
// the decode function)
SMDiagnostic err;
auto buf = MemoryBuffer::getMemBuffer(
StringRef(reinterpret_cast<const char *>(decode_c_bc), decode_c_bc_len),
"", false);
std::unique_ptr<Module> decodeModule =
parseIR(buf->getMemBufferRef(), err, ctx);
Function *loadedFunction = decodeModule->getFunction("decodeString");
// Declare the decode function in M with the same signature as the loaded
// function
auto functionName = generateRandomName();
M.getOrInsertFunction(functionName, loadedFunction->getFunctionType());
Function *declaredFunction = M.getFunction(functionName);
// Map the declared and loaded functions arguments
ValueToValueMapTy vmap;
auto larg = loadedFunction->arg_begin();
for (auto darg = declaredFunction->arg_begin();
darg != declaredFunction->arg_end(); darg++) {
vmap[&*larg] = &*darg;
larg++;
}
// Copy the loaded function into the empty declared function (in the proper
// module)
SmallVector<ReturnInst *, 8> returns;
ClonedCodeInfo codeInfo;
CloneFunctionInto(declaredFunction, loadedFunction, vmap,
#if LLVM_VERSION_MAJOR < 13
true,
#else
CloneFunctionChangeType::DifferentModule,
#endif
returns, "", &codeInfo);
return declaredFunction;
}
void StringObfuscatorPass::addDecodeAllStringsFunction(
Module &M, Function *decodeFunction) {
auto &ctx = M.getContext();
FunctionCallee callee =
M.getOrInsertFunction(generateRandomName(), Type::getVoidTy(ctx));
Function *decodeAllStrings = cast<Function>(callee.getCallee());
decodeAllStrings->setCallingConv(CallingConv::C);
BasicBlock *decodeBlock =
BasicBlock::Create(ctx, "decodeBlock", decodeAllStrings);
// Insert function calls to decodeFunction to decrypt each encrypted string
// in the main
IRBuilder<> builder(decodeBlock);
for (auto str : this->globalStrings) {
Value *array = str.var;
// If this is a struct we need to get a pointer to the array
// at the field index
if (str.isStruct) {
array = builder.CreateStructGEP(
str.var->getValueType(), str.var, str.index);
}
// Get a pointer to the first element of the array (start of the string).
// Use the actual array type [size x i8] as the GEP element type, not the
// pointer type returned by getType() (which is opaque ptr in LLVM >= 15).
auto arrayType = ArrayType::get(Type::getInt8Ty(ctx), str.size);
auto ptr = builder.CreateConstInBoundsGEP2_32(
arrayType, array, 0, 0);
// Get the size of the string
auto size = ConstantInt::get(IntegerType::getInt32Ty(ctx), str.size);
auto key = ConstantInt::get(IntegerType::getInt8Ty(ctx), str.key);
// Call the decode function
builder.CreateCall(decodeFunction, {ptr, size, key});
}
builder.CreateRetVoid();
// Add the function to global constructors
llvm::appendToGlobalCtors(M, decodeAllStrings, 0);
}
PreservedAnalyses StringObfuscatorPass::run(Module &M,
ModuleAnalysisManager &MAM) {
// Encode all the global strings
if (!encodeAllStrings(M)) {
return PreservedAnalyses::all();
}
// Insert a function to decode a string
Function *decodeFunction = addDecodeFunction(M);
// Insert a function decoding all the strings in global constructors
addDecodeAllStringsFunction(M, decodeFunction);
return PreservedAnalyses::none();
}
} // namespace llvm