feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固
- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测 - llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言) - tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化) - tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
@@ -0,0 +1,983 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallPtrSet.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/ADT/StringSet.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/DebugInfoMetadata.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalAlias.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicsAArch64.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Operator.h"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/TargetParser/Triple.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
void collectCompilerUsed(const Module &M, StringRef Name,
|
||||
SmallPtrSetImpl<const GlobalValue *> &Out) {
|
||||
const GlobalVariable *GV = M.getNamedGlobal(Name);
|
||||
if (!GV || !GV->hasInitializer())
|
||||
return;
|
||||
const auto *CA = dyn_cast<ConstantArray>(GV->getInitializer());
|
||||
if (!CA)
|
||||
return;
|
||||
for (const Use &U : CA->operands()) {
|
||||
if (const auto *Target = dyn_cast<GlobalValue>(U.get()->stripPointerCasts()))
|
||||
Out.insert(Target);
|
||||
}
|
||||
}
|
||||
|
||||
bool isPassThroughConstantExpr(const ConstantExpr *CE) {
|
||||
unsigned Op = CE->getOpcode();
|
||||
if (Op == Instruction::BitCast || Op == Instruction::AddrSpaceCast)
|
||||
return true;
|
||||
if (Op == Instruction::GetElementPtr) {
|
||||
if (const auto *GEP = dyn_cast<GEPOperator>(CE))
|
||||
return GEP->hasAllZeroIndices();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool containsRootValue(const Value *V, const GlobalVariable *Root,
|
||||
bool AllowSwiftBias) {
|
||||
if (V == Root)
|
||||
return true;
|
||||
const auto *CE = dyn_cast<ConstantExpr>(V);
|
||||
if (!CE)
|
||||
return false;
|
||||
if (isPassThroughConstantExpr(CE))
|
||||
return containsRootValue(CE->getOperand(0), Root, AllowSwiftBias);
|
||||
if (!AllowSwiftBias)
|
||||
return false;
|
||||
switch (CE->getOpcode()) {
|
||||
case Instruction::PtrToInt:
|
||||
case Instruction::IntToPtr:
|
||||
return containsRootValue(CE->getOperand(0), Root, true);
|
||||
case Instruction::Sub:
|
||||
return isa<ConstantInt>(CE->getOperand(1)) &&
|
||||
containsRootValue(CE->getOperand(0), Root, true);
|
||||
case Instruction::Add:
|
||||
case Instruction::Or: {
|
||||
bool LeftRoot = isa<ConstantInt>(CE->getOperand(1)) &&
|
||||
containsRootValue(CE->getOperand(0), Root, true);
|
||||
bool RightRoot = isa<ConstantInt>(CE->getOperand(0)) &&
|
||||
containsRootValue(CE->getOperand(1), Root, true);
|
||||
return LeftRoot || RightRoot;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const Value *unwrapBaseValue(const Value *V) {
|
||||
while (const auto *CE = dyn_cast<ConstantExpr>(V)) {
|
||||
if (!isPassThroughConstantExpr(CE))
|
||||
break;
|
||||
V = CE->getOperand(0);
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
bool isSafePhiPredBlock(const BasicBlock *PredBB) {
|
||||
if (!PredBB || PredBB->isEHPad())
|
||||
return false;
|
||||
const Instruction *Term = PredBB->getTerminator();
|
||||
if (!Term || isa<CatchSwitchInst>(Term) || isa<IndirectBrInst>(Term))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Verify that EVERY transitive user of Root is a controlled instruction inside
|
||||
// a function matching FnPred (or safe predecessor edges of PHINodes).
|
||||
bool collectControlledUsersEx(const GlobalVariable *Root, bool AllowSwiftBias,
|
||||
function_ref<bool(const Function &)> FnPred,
|
||||
SmallVectorImpl<Instruction *> &OutInsts) {
|
||||
SmallVector<const Value *, 8> Worklist{Root};
|
||||
SmallPtrSet<const Value *, 8> Visited{Root};
|
||||
SmallPtrSet<Instruction *, 8> SeenInsts;
|
||||
|
||||
while (!Worklist.empty()) {
|
||||
const Value *Cur = Worklist.pop_back_val();
|
||||
for (const Use &U : Cur->uses()) {
|
||||
const User *Usr = U.getUser();
|
||||
if (const auto *CE = dyn_cast<ConstantExpr>(Usr)) {
|
||||
if (!containsRootValue(CE, Root, AllowSwiftBias))
|
||||
return false;
|
||||
if (Visited.insert(CE).second)
|
||||
Worklist.push_back(CE);
|
||||
continue;
|
||||
}
|
||||
if (isa<Constant>(Usr))
|
||||
return false;
|
||||
|
||||
const auto *Inst = dyn_cast<Instruction>(Usr);
|
||||
if (!Inst || !Inst->getParent() || Inst->getParent()->isEHPad())
|
||||
return false;
|
||||
if (isa<LandingPadInst>(Inst) || Inst->isEHPad())
|
||||
return false;
|
||||
if (const auto *CB = dyn_cast<CallBase>(Inst)) {
|
||||
if (&U == &CB->getCalledOperandUse())
|
||||
return false;
|
||||
}
|
||||
|
||||
if (const auto *PN = dyn_cast<PHINode>(Inst)) {
|
||||
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
|
||||
if (PN->getIncomingValue(i) == Cur &&
|
||||
!isSafePhiPredBlock(PN->getIncomingBlock(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Function *ParentF = Inst->getFunction();
|
||||
if (!ParentF || !FnPred(*ParentF))
|
||||
return false;
|
||||
|
||||
Instruction *MutableInst = const_cast<Instruction *>(Inst);
|
||||
if (SeenInsts.insert(MutableInst).second)
|
||||
OutInsts.push_back(MutableInst);
|
||||
}
|
||||
}
|
||||
return !OutInsts.empty();
|
||||
}
|
||||
|
||||
Value *materializeValueForRoot(IRBuilder<> &B, Value *Orig,
|
||||
const GlobalVariable *Root, Value *Replacement) {
|
||||
if (Orig == Root)
|
||||
return Replacement;
|
||||
auto *CE = dyn_cast<ConstantExpr>(Orig);
|
||||
if (!CE)
|
||||
return Orig;
|
||||
switch (CE->getOpcode()) {
|
||||
case Instruction::BitCast: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateBitCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::AddrSpaceCast: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateAddrSpaceCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::GetElementPtr: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateBitCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::PtrToInt: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreatePtrToInt(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::IntToPtr: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateIntToPtr(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::Sub: {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateSub(LHS, CE->getOperand(1));
|
||||
}
|
||||
case Instruction::Add: {
|
||||
if (containsRootValue(CE->getOperand(0), Root, true)) {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateAdd(LHS, CE->getOperand(1));
|
||||
}
|
||||
Value *RHS =
|
||||
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
|
||||
return B.CreateAdd(CE->getOperand(0), RHS);
|
||||
}
|
||||
case Instruction::Or: {
|
||||
if (containsRootValue(CE->getOperand(0), Root, true)) {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateOr(LHS, CE->getOperand(1));
|
||||
}
|
||||
Value *RHS =
|
||||
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
|
||||
return B.CreateOr(CE->getOperand(0), RHS);
|
||||
}
|
||||
default:
|
||||
return Orig;
|
||||
}
|
||||
}
|
||||
|
||||
void rewriteUsersWithDecryptFn(
|
||||
GlobalVariable *RootGV, Function *DecFn, bool AllowSwiftBias,
|
||||
ArrayRef<Instruction *> LeafInsts, StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions) {
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
if (auto *PN = dyn_cast<PHINode>(UI)) {
|
||||
DenseMap<std::pair<BasicBlock *, Value *>, Value *> EdgeCache;
|
||||
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
|
||||
Value *InVal = PN->getIncomingValue(i);
|
||||
if (!containsRootValue(InVal, RootGV, AllowSwiftBias))
|
||||
continue;
|
||||
BasicBlock *PredBB = PN->getIncomingBlock(i);
|
||||
auto CacheKey = std::make_pair(PredBB, InVal);
|
||||
Value *ReplVal = nullptr;
|
||||
auto It = EdgeCache.find(CacheKey);
|
||||
if (It != EdgeCache.end()) {
|
||||
ReplVal = It->second;
|
||||
} else {
|
||||
Instruction *Term = PredBB->getTerminator();
|
||||
IRBuilder<> EdgeB(Term);
|
||||
CallInst *DecCall = EdgeB.CreateCall(DecFn, {}, "ig.str");
|
||||
DecCall->setDebugLoc(Term->getDebugLoc());
|
||||
ReplVal = AllowSwiftBias
|
||||
? materializeValueForRoot(EdgeB, InVal, RootGV, DecCall)
|
||||
: static_cast<Value *>(DecCall);
|
||||
EdgeCache[CacheKey] = ReplVal;
|
||||
}
|
||||
PN->setIncomingValue(i, ReplVal);
|
||||
}
|
||||
} else {
|
||||
IRBuilder<> B(UI);
|
||||
CallInst *DecCall = B.CreateCall(DecFn, {}, "ig.str");
|
||||
DecCall->setDebugLoc(UI->getDebugLoc());
|
||||
for (unsigned i = 0, e = UI->getNumOperands(); i < e; ++i) {
|
||||
Value *Op = UI->getOperand(i);
|
||||
if (containsRootValue(Op, RootGV, AllowSwiftBias)) {
|
||||
Value *ReplVal = AllowSwiftBias
|
||||
? materializeValueForRoot(B, Op, RootGV, DecCall)
|
||||
: static_cast<Value *>(DecCall);
|
||||
UI->setOperand(i, ReplVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const Function *ParentF = UI->getFunction()) {
|
||||
if (SeenFunctions.insert(ParentF->getName()).second)
|
||||
TouchedFunctions.push_back(ParentF->getName().str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Function *createDecryptFunction(Module &M, uint64_t Id, StringRef FnPrefix,
|
||||
GlobalVariable *EncGV, GlobalVariable *KeyGV,
|
||||
GlobalVariable *BufGV, GlobalVariable *StateGV,
|
||||
GlobalVariable *RetGV, uint64_t Len,
|
||||
Align BufAlign) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *PtrTy = PointerType::getUnqual(Ctx);
|
||||
Type *I32Ty = Type::getInt32Ty(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
ArrayType *ArrTy = ArrayType::get(I8Ty, Len);
|
||||
|
||||
FunctionType *FnTy = FunctionType::get(PtrTy, false);
|
||||
std::string FnName = (FnPrefix + Twine(Id)).str();
|
||||
Function *Fn =
|
||||
Function::Create(FnTy, GlobalValue::InternalLinkage, FnName, &M);
|
||||
Fn->addFnAttr(Attribute::NoInline);
|
||||
Fn->addFnAttr(Attribute::NoBuiltin);
|
||||
Fn->addFnAttr(Attribute::NoUnwind);
|
||||
Fn->setDSOLocal(true);
|
||||
|
||||
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
|
||||
BasicBlock *CasBB = BasicBlock::Create(Ctx, "cas", Fn);
|
||||
BasicBlock *WaitBB = BasicBlock::Create(Ctx, "wait", Fn);
|
||||
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
|
||||
BasicBlock *DoneBB = BasicBlock::Create(Ctx, "done", Fn);
|
||||
BasicBlock *RetBB = BasicBlock::Create(Ctx, "ret", Fn);
|
||||
|
||||
// Entry: fast path acquire load == 2
|
||||
IRBuilder<> B(EntryBB);
|
||||
LoadInst *FastState = B.CreateLoad(I32Ty, StateGV, false, "st.fast");
|
||||
FastState->setAlignment(Align(4));
|
||||
FastState->setAtomic(AtomicOrdering::Acquire);
|
||||
Value *Ready =
|
||||
B.CreateICmpEQ(FastState, ConstantInt::get(I32Ty, 2), "is.ready");
|
||||
B.CreateCondBr(Ready, RetBB, CasBB);
|
||||
|
||||
// CAS: try claiming 0 -> 1
|
||||
B.SetInsertPoint(CasBB);
|
||||
AtomicCmpXchgInst *CX = B.CreateAtomicCmpXchg(
|
||||
StateGV, ConstantInt::get(I32Ty, 0), ConstantInt::get(I32Ty, 1),
|
||||
Align(4), AtomicOrdering::AcquireRelease, AtomicOrdering::Acquire);
|
||||
Value *Won = B.CreateExtractValue(CX, 1, "won");
|
||||
B.CreateCondBr(Won, LoopBB, WaitBB);
|
||||
|
||||
// Wait: spin with optional AArch64 yield hint until winner releases 2
|
||||
B.SetInsertPoint(WaitBB);
|
||||
if (Triple(M.getTargetTriple()).isAArch64()) {
|
||||
Function *HintFn =
|
||||
Intrinsic::getOrInsertDeclaration(&M, Intrinsic::aarch64_hint);
|
||||
B.CreateCall(HintFn, {ConstantInt::get(I32Ty, 1)});
|
||||
}
|
||||
LoadInst *WaitState = B.CreateLoad(I32Ty, StateGV, false, "st.wait");
|
||||
WaitState->setAlignment(Align(4));
|
||||
WaitState->setAtomic(AtomicOrdering::Acquire);
|
||||
Value *NowReady =
|
||||
B.CreateICmpEQ(WaitState, ConstantInt::get(I32Ty, 2), "wait.ready");
|
||||
B.CreateCondBr(NowReady, RetBB, WaitBB);
|
||||
|
||||
// Loop: volatile decrypt bytes from enc ^ key into internal global buffer
|
||||
B.SetInsertPoint(LoopBB);
|
||||
PHINode *Idx = B.CreatePHI(I64Ty, 2, "idx");
|
||||
Idx->addIncoming(ConstantInt::get(I64Ty, 0), CasBB);
|
||||
Value *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
Value *EncPtr = B.CreateInBoundsGEP(ArrTy, EncGV, {Zero64, Idx}, "enc.ptr");
|
||||
Value *KeyPtr = B.CreateInBoundsGEP(ArrTy, KeyGV, {Zero64, Idx}, "key.ptr");
|
||||
Value *BufPtr = B.CreateInBoundsGEP(ArrTy, BufGV, {Zero64, Idx}, "buf.ptr");
|
||||
LoadInst *EncByte = B.CreateLoad(I8Ty, EncPtr, /*isVolatile=*/true, "eb");
|
||||
LoadInst *KeyByte = B.CreateLoad(I8Ty, KeyPtr, /*isVolatile=*/true, "kb");
|
||||
Value *PlainByte = B.CreateXor(EncByte, KeyByte, "pb");
|
||||
StoreInst *St = B.CreateStore(PlainByte, BufPtr, /*isVolatile=*/true);
|
||||
St->setAlignment(Align(1));
|
||||
(void)BufAlign;
|
||||
Value *NextIdx =
|
||||
B.CreateAdd(Idx, ConstantInt::get(I64Ty, 1), "next", /*HasNUW=*/true);
|
||||
Idx->addIncoming(NextIdx, LoopBB);
|
||||
Value *LoopDone =
|
||||
B.CreateICmpEQ(NextIdx, ConstantInt::get(I64Ty, Len), "loop.done");
|
||||
B.CreateCondBr(LoopDone, DoneBB, LoopBB);
|
||||
|
||||
// Done: release store 2 so waiting and future callers observe decrypted bytes
|
||||
B.SetInsertPoint(DoneBB);
|
||||
StoreInst *Publish =
|
||||
B.CreateStore(ConstantInt::get(I32Ty, 2), StateGV, false);
|
||||
Publish->setAlignment(Align(4));
|
||||
Publish->setAtomic(AtomicOrdering::Release);
|
||||
B.CreateBr(RetBB);
|
||||
|
||||
// Ret: return target object base pointer (BufGV or CFConstantString)
|
||||
B.SetInsertPoint(RetBB);
|
||||
B.CreateRet(RetGV);
|
||||
|
||||
return Fn;
|
||||
}
|
||||
|
||||
bool isStackAllowlistedCallee(StringRef RawName, bool &OutIsStrstr,
|
||||
bool &OutIsMemcpySrc) {
|
||||
OutIsStrstr = false;
|
||||
OutIsMemcpySrc = false;
|
||||
StringRef Name = RawName;
|
||||
if (Name.starts_with("\x01_"))
|
||||
Name = Name.drop_front(2);
|
||||
else if (Name.starts_with("\x01"))
|
||||
Name = Name.drop_front(1);
|
||||
if (Name == "strstr") {
|
||||
OutIsStrstr = true;
|
||||
return true;
|
||||
}
|
||||
if (Name.starts_with("llvm.memcpy.")) {
|
||||
OutIsMemcpySrc = true;
|
||||
return true;
|
||||
}
|
||||
static constexpr const char *kAllowed[] = {
|
||||
"strcmp", "strncmp",
|
||||
"strcasecmp", "strncasecmp",
|
||||
"strlen", "memcmp",
|
||||
"access", "stat",
|
||||
"lstat", "open",
|
||||
"fopen", "dlopen",
|
||||
"dlsym", "getenv",
|
||||
"sysctlbyname", "IG_dispatch_open",
|
||||
"IG_dispatch_stat", "IG_dispatch_lstat",
|
||||
"IG_dispatch_access", "ig_ends_with",
|
||||
"ig_strncmp", "ig_strcmp",
|
||||
"ig_strlen",
|
||||
};
|
||||
for (const char *Allowed : kAllowed) {
|
||||
if (Name == Allowed)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool canUseMultiFnStackDecrypt(const GlobalVariable *GV, uint64_t Len,
|
||||
const IGPolicyConfig &Policy,
|
||||
ArrayRef<Instruction *> LeafInsts) {
|
||||
uint64_t MaxStackLen = Policy.stringEncryptStackMaxLen();
|
||||
if (MaxStackLen == 0 || Len == 0 || Len > MaxStackLen || LeafInsts.empty())
|
||||
return false;
|
||||
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
auto *CI = dyn_cast<CallInst>(UI);
|
||||
if (!CI || CI->isMustTailCall() || CI->isInlineAsm())
|
||||
return false;
|
||||
Function *ParentF = CI->getFunction();
|
||||
if (!ParentF || ParentF->empty() || ParentF->getEntryBlock().isEHPad() ||
|
||||
!Policy.shouldStackEncryptStringsInFunction(*ParentF)) {
|
||||
return false;
|
||||
}
|
||||
Function *Callee = CI->getCalledFunction();
|
||||
if (!Callee)
|
||||
return false;
|
||||
bool IsStrstr = false;
|
||||
bool IsMemcpySrc = false;
|
||||
if (!isStackAllowlistedCallee(Callee->getName(), IsStrstr, IsMemcpySrc))
|
||||
return false;
|
||||
|
||||
bool FoundOp = false;
|
||||
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
|
||||
Value *Op = CI->getOperand(i);
|
||||
if (unwrapBaseValue(Op) == GV) {
|
||||
if (!CI->isArgOperand(&CI->getOperandUse(i)) ||
|
||||
!Op->getType()->isPointerTy() ||
|
||||
Op->stripPointerCasts() != GV) {
|
||||
return false;
|
||||
}
|
||||
if ((IsStrstr || IsMemcpySrc) && i != 1)
|
||||
return false;
|
||||
FoundOp = true;
|
||||
}
|
||||
}
|
||||
if (!FoundOp)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Function *getOrCreateStackDecryptFn(Module &M) {
|
||||
if (Function *Existing = M.getFunction("__ig_str_dec_stack"))
|
||||
return Existing;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *PtrTy = PointerType::getUnqual(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Ctx),
|
||||
{PtrTy, PtrTy, PtrTy, I64Ty}, false);
|
||||
Function *Fn = Function::Create(FnTy, GlobalValue::InternalLinkage,
|
||||
"__ig_str_dec_stack", &M);
|
||||
Fn->addFnAttr(Attribute::NoInline);
|
||||
Fn->addFnAttr(Attribute::NoUnwind);
|
||||
|
||||
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
|
||||
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
|
||||
BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", Fn);
|
||||
|
||||
Value *Dst = Fn->getArg(0);
|
||||
Value *Enc = Fn->getArg(1);
|
||||
Value *Key = Fn->getArg(2);
|
||||
Value *LenArg = Fn->getArg(3);
|
||||
|
||||
IRBuilder<> EB(EntryBB);
|
||||
Value *HasBytes = EB.CreateICmpUGT(LenArg, ConstantInt::get(I64Ty, 0));
|
||||
EB.CreateCondBr(HasBytes, LoopBB, ExitBB);
|
||||
|
||||
IRBuilder<> LB(LoopBB);
|
||||
PHINode *Idx = LB.CreatePHI(I64Ty, 2, "idx");
|
||||
Idx->addIncoming(ConstantInt::get(I64Ty, 0), EntryBB);
|
||||
Value *EncPtr = LB.CreateInBoundsGEP(I8Ty, Enc, Idx);
|
||||
Value *KeyPtr = LB.CreateInBoundsGEP(I8Ty, Key, Idx);
|
||||
Value *DstPtr = LB.CreateInBoundsGEP(I8Ty, Dst, Idx);
|
||||
Value *EncByte = LB.CreateAlignedLoad(I8Ty, EncPtr, Align(1));
|
||||
Value *KeyByte = LB.CreateAlignedLoad(I8Ty, KeyPtr, Align(1));
|
||||
Value *DecByte = LB.CreateXor(EncByte, KeyByte);
|
||||
LB.CreateAlignedStore(DecByte, DstPtr, Align(1));
|
||||
Value *NextIdx = LB.CreateAdd(Idx, ConstantInt::get(I64Ty, 1));
|
||||
Idx->addIncoming(NextIdx, LoopBB);
|
||||
Value *Cont = LB.CreateICmpULT(NextIdx, LenArg);
|
||||
LB.CreateCondBr(Cont, LoopBB, ExitBB);
|
||||
|
||||
IRBuilder<> XB(ExitBB);
|
||||
XB.CreateRetVoid();
|
||||
return Fn;
|
||||
}
|
||||
|
||||
void emitEncryptedKeyPair(Module &M, uint64_t CurId, StringRef RawBytes,
|
||||
StringRef Seed, StringRef ItemId, Align BufAlign,
|
||||
bool EmitGlobalBuf, GlobalVariable *&OutEncGV,
|
||||
GlobalVariable *&OutKeyGV,
|
||||
GlobalVariable *&OutBufGV,
|
||||
GlobalVariable *&OutStateGV) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
uint64_t Len = RawBytes.size();
|
||||
IGDeterministicRNG RNG(Seed, M.getModuleIdentifier(), ItemId);
|
||||
SmallVector<uint8_t, 64> KeyBytes(Len);
|
||||
SmallVector<uint8_t, 64> EncBytes(Len);
|
||||
for (size_t i = 0; i < Len; ++i) {
|
||||
uint8_t K = RNG.nextNonZeroByte();
|
||||
KeyBytes[i] = K;
|
||||
EncBytes[i] = static_cast<uint8_t>(RawBytes[i]) ^ K;
|
||||
}
|
||||
|
||||
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
|
||||
OutEncGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
|
||||
ConstantDataArray::get(Ctx, EncBytes), ".ig.enc." + Twine(CurId));
|
||||
OutEncGV->setAlignment(Align(1));
|
||||
OutEncGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
|
||||
|
||||
OutKeyGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
|
||||
ConstantDataArray::get(Ctx, KeyBytes), ".ig.key." + Twine(CurId));
|
||||
OutKeyGV->setAlignment(Align(1));
|
||||
OutKeyGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
|
||||
|
||||
OutBufGV = nullptr;
|
||||
OutStateGV = nullptr;
|
||||
if (EmitGlobalBuf) {
|
||||
OutBufGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
|
||||
ConstantAggregateZero::get(ArrTy), ".ig.buf." + Twine(CurId));
|
||||
OutBufGV->setAlignment(BufAlign);
|
||||
|
||||
Type *I32Ty = Type::getInt32Ty(Ctx);
|
||||
OutStateGV = new GlobalVariable(
|
||||
M, I32Ty, /*isConstant=*/false, GlobalValue::InternalLinkage,
|
||||
ConstantInt::get(I32Ty, 0), ".ig.state." + Twine(CurId));
|
||||
OutStateGV->setAlignment(Align(4));
|
||||
}
|
||||
}
|
||||
|
||||
void applyStackDecryptAndWipe(Module &M, GlobalVariable *GV, uint64_t CurId,
|
||||
GlobalVariable *EncGV, GlobalVariable *KeyGV,
|
||||
uint64_t Len, ArrayRef<Instruction *> LeafInsts,
|
||||
StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
|
||||
Function *StackDecFn = getOrCreateStackDecryptFn(M);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
Constant *Zero8 = ConstantInt::get(I8Ty, 0);
|
||||
Constant *LenConst = ConstantInt::get(I64Ty, Len);
|
||||
|
||||
DenseMap<Function *, AllocaInst *> FuncBufs;
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
auto *CI = cast<CallInst>(UI);
|
||||
Function *ParentF = CI->getFunction();
|
||||
AllocaInst *&StackBuf = FuncBufs[ParentF];
|
||||
if (!StackBuf) {
|
||||
BasicBlock &TargetEntry = ParentF->getEntryBlock();
|
||||
BasicBlock::iterator AllocaInsPt = TargetEntry.begin();
|
||||
while (AllocaInsPt != TargetEntry.end() && isa<AllocaInst>(AllocaInsPt))
|
||||
++AllocaInsPt;
|
||||
IRBuilder<> AllocaB(&TargetEntry, AllocaInsPt);
|
||||
StackBuf = AllocaB.CreateAlloca(ArrTy, nullptr, "ig.sbuf." + Twine(CurId));
|
||||
StackBuf->setAlignment(Align(1));
|
||||
if (SeenFunctions.insert(ParentF->getName()).second)
|
||||
TouchedFunctions.push_back(ParentF->getName().str());
|
||||
}
|
||||
|
||||
DebugLoc DbgLoc = CI->getDebugLoc();
|
||||
IRBuilder<> PreB(CI);
|
||||
CallInst *DecCall =
|
||||
PreB.CreateCall(StackDecFn, {StackBuf, EncGV, KeyGV, LenConst});
|
||||
DecCall->setDebugLoc(DbgLoc);
|
||||
|
||||
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
|
||||
if (unwrapBaseValue(CI->getOperand(i)) == GV)
|
||||
CI->setOperand(i, StackBuf);
|
||||
}
|
||||
|
||||
if (Len <= 64) {
|
||||
IRBuilder<> AfterB(CI->getNextNode());
|
||||
for (uint64_t k = 0; k < Len; ++k) {
|
||||
Value *BytePtr = AfterB.CreateInBoundsGEP(
|
||||
ArrTy, StackBuf, {Zero64, ConstantInt::get(I64Ty, k)});
|
||||
StoreInst *WipeStore = AfterB.CreateAlignedStore(
|
||||
Zero8, BytePtr, Align(1), /*isVolatile=*/true);
|
||||
WipeStore->setDebugLoc(DbgLoc);
|
||||
}
|
||||
} else {
|
||||
BasicBlock *CurBB = CI->getParent();
|
||||
BasicBlock *ContBB = CurBB->splitBasicBlock(
|
||||
CI->getNextNode(), "ig.wipe.cont." + Twine(CurId));
|
||||
BasicBlock *WipeBB = BasicBlock::Create(
|
||||
Ctx, "ig.wipe.loop." + Twine(CurId), ParentF, ContBB);
|
||||
CurBB->getTerminator()->eraseFromParent();
|
||||
IRBuilder<> BrB(CurBB);
|
||||
BrB.SetCurrentDebugLocation(DbgLoc);
|
||||
BrB.CreateBr(WipeBB);
|
||||
|
||||
IRBuilder<> WB(WipeBB);
|
||||
WB.SetCurrentDebugLocation(DbgLoc);
|
||||
PHINode *WIdx = WB.CreatePHI(I64Ty, 2, "widx");
|
||||
WIdx->addIncoming(Zero64, CurBB);
|
||||
Value *BytePtr = WB.CreateInBoundsGEP(ArrTy, StackBuf, {Zero64, WIdx});
|
||||
WB.CreateAlignedStore(Zero8, BytePtr, Align(1), /*isVolatile=*/true);
|
||||
Value *NextWIdx = WB.CreateAdd(WIdx, ConstantInt::get(I64Ty, 1));
|
||||
WIdx->addIncoming(NextWIdx, WipeBB);
|
||||
Value *More = WB.CreateICmpULT(NextWIdx, LenConst);
|
||||
WB.CreateCondBr(More, WipeBB, ContBB);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool hasAnyNonZeroBytes(StringRef Raw) {
|
||||
for (unsigned char C : Raw) {
|
||||
if (C != 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool tryEncryptCFConstantString(
|
||||
Module &M, GlobalVariable *CFGV, const IGPolicyConfig &Policy,
|
||||
const SmallPtrSet<const GlobalValue *, 16> &PreservedUsed,
|
||||
const SmallPtrSet<const GlobalVariable *, 16> &AliasedGlobals,
|
||||
uint64_t &NextId, StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions, IGAuditRecord &Audit) {
|
||||
if (!CFGV->hasInitializer() || !CFGV->hasLocalLinkage() ||
|
||||
CFGV->isThreadLocal() || CFGV->getSection() != "__DATA,__cfstring") {
|
||||
return false;
|
||||
}
|
||||
if (PreservedUsed.contains(CFGV) || AliasedGlobals.contains(CFGV))
|
||||
return false;
|
||||
|
||||
const auto *CS = dyn_cast<ConstantStruct>(CFGV->getInitializer());
|
||||
if (!CS || CS->getNumOperands() != 4)
|
||||
return false;
|
||||
|
||||
const auto *ClassGV =
|
||||
dyn_cast<GlobalValue>(CS->getOperand(0)->stripPointerCasts());
|
||||
if (!ClassGV || ClassGV->getName() != "__CFConstantStringClassReference")
|
||||
return false;
|
||||
|
||||
const auto *FlagsCI = dyn_cast<ConstantInt>(CS->getOperand(1));
|
||||
const auto *LenCI = dyn_cast<ConstantInt>(CS->getOperand(3));
|
||||
if (!FlagsCI || !LenCI)
|
||||
return false;
|
||||
uint64_t Flags = FlagsCI->getZExtValue();
|
||||
uint64_t CharCount = LenCI->getZExtValue();
|
||||
if ((Flags != 1992 && Flags != 2000) || CharCount < 4)
|
||||
return false;
|
||||
|
||||
auto *StrGV = dyn_cast<GlobalVariable>(CS->getOperand(2)->stripPointerCasts());
|
||||
if (!StrGV || !StrGV->hasInitializer() || !StrGV->isConstant() ||
|
||||
!StrGV->hasLocalLinkage() || PreservedUsed.contains(StrGV) ||
|
||||
AliasedGlobals.contains(StrGV) || !StrGV->hasOneUse()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(StrGV->getInitializer());
|
||||
if (!CDS || CDS->getNumElements() != CharCount + 1)
|
||||
return false;
|
||||
bool IsUTF16 = (Flags == 2000);
|
||||
if (IsUTF16 && !CDS->getElementType()->isIntegerTy(16))
|
||||
return false;
|
||||
if (!IsUTF16 && !CDS->getElementType()->isIntegerTy(8))
|
||||
return false;
|
||||
if (CDS->getElementAsInteger(CharCount) != 0)
|
||||
return false;
|
||||
|
||||
StringRef Raw = CDS->getRawDataValues();
|
||||
if (Raw.empty() || !hasAnyNonZeroBytes(Raw))
|
||||
return false;
|
||||
|
||||
SmallVector<Instruction *, 8> LeafInsts;
|
||||
auto FnPred = [&](const Function &F) {
|
||||
return Policy.shouldEncryptObjCStringsInFunction(F) ||
|
||||
Policy.shouldEncryptSwiftStringsInFunction(F);
|
||||
};
|
||||
if (!collectControlledUsersEx(CFGV, /*AllowSwiftBias=*/false, FnPred,
|
||||
LeafInsts)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t CurId = NextId++;
|
||||
Align BufAlign(IsUTF16 ? 2 : 1);
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), StrGV->getName(), BufAlign,
|
||||
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
|
||||
|
||||
Constant *NewCFInit = ConstantStruct::get(
|
||||
CS->getType(),
|
||||
{CS->getOperand(0), CS->getOperand(1), BufGV, CS->getOperand(3)});
|
||||
CFGV->setInitializer(NewCFInit);
|
||||
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_cf_", EncGV, KeyGV, BufGV,
|
||||
StateGV, CFGV, Raw.size(), BufAlign);
|
||||
|
||||
rewriteUsersWithDecryptFn(CFGV, DecFn, /*AllowSwiftBias=*/false, LeafInsts,
|
||||
SeenFunctions, TouchedFunctions);
|
||||
|
||||
StrGV->removeDeadConstantUsers();
|
||||
if (StrGV->use_empty())
|
||||
StrGV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Audit.ObjCStringsEncryptedCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runSourcePathScrubbing(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
const auto &Substrings = Policy.scrubPathSubstrings();
|
||||
std::string SwiftModPrefix;
|
||||
if (!Policy.swiftModuleName().empty())
|
||||
SwiftModPrefix = Policy.swiftModuleName().str() + "/";
|
||||
|
||||
if (Substrings.empty() && SwiftModPrefix.empty())
|
||||
return false;
|
||||
|
||||
bool Changed = false;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
|
||||
for (GlobalVariable &GV : M.globals()) {
|
||||
if (!GV.hasInitializer() || !GV.isConstant() || !GV.hasLocalLinkage())
|
||||
continue;
|
||||
if (GV.hasSection() || GV.isThreadLocal())
|
||||
continue;
|
||||
StringRef Name = GV.getName();
|
||||
if (Name == "llvm.global.annotations" || Name.starts_with(".ig.") ||
|
||||
Name.starts_with("__ig_"))
|
||||
continue;
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV.getInitializer());
|
||||
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
|
||||
continue;
|
||||
|
||||
StringRef S = CDS->getAsCString();
|
||||
if (S.empty())
|
||||
continue;
|
||||
|
||||
bool IsSourceExt = S.ends_with(".swift") || S.ends_with(".m") ||
|
||||
S.ends_with(".mm") || S.ends_with(".c") ||
|
||||
S.ends_with(".h");
|
||||
bool Matched = false;
|
||||
for (const std::string &Sub : Substrings) {
|
||||
if (!Sub.empty() && S.contains(Sub)) {
|
||||
Matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!Matched && IsSourceExt &&
|
||||
(S.starts_with("./readoor/") || S.starts_with("readoor/") ||
|
||||
S.contains("/readoor/"))) {
|
||||
Matched = true;
|
||||
}
|
||||
if (!Matched && !SwiftModPrefix.empty() &&
|
||||
S.starts_with(SwiftModPrefix) && S.ends_with(".swift")) {
|
||||
Matched = true;
|
||||
}
|
||||
if (!Matched)
|
||||
continue;
|
||||
|
||||
SHA256 Hasher;
|
||||
Hasher.update(Policy.seed());
|
||||
Hasher.update("|");
|
||||
Hasher.update(S);
|
||||
auto Digest = Hasher.final();
|
||||
std::string Tag8 = toHex(ArrayRef<uint8_t>(Digest.data(), 4), /*LowerCase=*/true);
|
||||
|
||||
std::string Repl = "ig_p_" + Tag8;
|
||||
if (Repl.size() < S.size())
|
||||
Repl.append(S.size() - Repl.size(), ' ');
|
||||
else if (Repl.size() > S.size())
|
||||
Repl.resize(S.size());
|
||||
|
||||
Constant *NewInit = ConstantDataArray::getString(Ctx, Repl, /*AddNull=*/true);
|
||||
if (NewInit->getType() != GV.getValueType())
|
||||
continue;
|
||||
|
||||
GV.setInitializer(NewInit);
|
||||
Audit.PathsScrubbedCount++;
|
||||
Changed = true;
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
bool runStringEncryption(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
SmallPtrSet<const GlobalValue *, 16> PreservedUsed;
|
||||
collectCompilerUsed(M, "llvm.used", PreservedUsed);
|
||||
collectCompilerUsed(M, "llvm.compiler.used", PreservedUsed);
|
||||
|
||||
SmallPtrSet<const GlobalVariable *, 16> AliasedGlobals;
|
||||
for (const GlobalAlias &GA : M.aliases()) {
|
||||
if (const auto *AliaseeGV =
|
||||
dyn_cast<GlobalVariable>(GA.getAliasee()->stripPointerCasts())) {
|
||||
AliasedGlobals.insert(AliaseeGV);
|
||||
}
|
||||
}
|
||||
|
||||
SmallVector<GlobalVariable *, 32> Candidates;
|
||||
for (GlobalVariable &GV : M.globals()) {
|
||||
Candidates.push_back(&GV);
|
||||
}
|
||||
|
||||
bool Changed = false;
|
||||
uint64_t NextId = 0;
|
||||
StringSet<> SeenFunctions;
|
||||
std::vector<std::string> TouchedFunctions;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
|
||||
const auto &ReplaceRules = Policy.stringReplaceRules();
|
||||
if (!ReplaceRules.empty()) {
|
||||
for (GlobalVariable *GV : Candidates) {
|
||||
if (!GV->hasInitializer() || !GV->isConstant() ||
|
||||
!GV->hasLocalLinkage() || GV->hasSection() || GV->isThreadLocal() ||
|
||||
GV->getName().starts_with(".ig.") ||
|
||||
GV->getName().starts_with("__ig_") ||
|
||||
PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
|
||||
continue;
|
||||
}
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
|
||||
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
|
||||
continue;
|
||||
StringRef CStr = CDS->getAsCString();
|
||||
for (const StringReplaceRule &Rule : ReplaceRules) {
|
||||
if (Rule.Exact == CStr) {
|
||||
uint64_t TotalLen = CDS->getNumElements();
|
||||
if (TotalLen < 2)
|
||||
break;
|
||||
SmallVector<uint8_t, 64> Buf(TotalLen, 0);
|
||||
size_t CopyLen = std::min<size_t>(Rule.Replace.size(), TotalLen - 1);
|
||||
if (CopyLen > 0)
|
||||
std::memcpy(Buf.data(), Rule.Replace.data(), CopyLen);
|
||||
GV->setInitializer(ConstantDataArray::get(Ctx, Buf));
|
||||
Audit.StringsReplacedCount++;
|
||||
Changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (GlobalVariable *GV : Candidates) {
|
||||
if (tryEncryptCFConstantString(M, GV, Policy, PreservedUsed, AliasedGlobals,
|
||||
NextId, SeenFunctions, TouchedFunctions,
|
||||
Audit)) {
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!GV->hasInitializer() || !GV->isConstant())
|
||||
continue;
|
||||
if (!GV->hasLocalLinkage())
|
||||
continue;
|
||||
if (GV->hasSection() || GV->isThreadLocal())
|
||||
continue;
|
||||
if (GV->getName().starts_with(".ig.") ||
|
||||
GV->getName().starts_with("__ig_"))
|
||||
continue;
|
||||
if (PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
|
||||
Audit.StringsSkippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
|
||||
if (!CDS || (!CDS->isString() && !CDS->isCString()) ||
|
||||
!CDS->getElementType()->isIntegerTy(8)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
StringRef Raw = CDS->getRawDataValues();
|
||||
if (Raw.size() < 5) // Require >= 4 non-trivial bytes (+ optional NUL)
|
||||
continue;
|
||||
if (!hasAnyNonZeroBytes(Raw))
|
||||
continue;
|
||||
|
||||
SmallVector<Instruction *, 8> LeafInsts;
|
||||
bool MatchedC = collectControlledUsersEx(
|
||||
GV, /*AllowSwiftBias=*/false,
|
||||
[&](const Function &F) {
|
||||
return Policy.shouldEncryptStringsInFunction(F);
|
||||
},
|
||||
LeafInsts);
|
||||
|
||||
if (MatchedC) {
|
||||
uint64_t CurId = NextId++;
|
||||
bool UseStack = canUseMultiFnStackDecrypt(GV, Raw.size(), Policy, LeafInsts);
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(1),
|
||||
/*EmitGlobalBuf=*/!UseStack, EncGV, KeyGV, BufGV,
|
||||
StateGV);
|
||||
|
||||
if (UseStack) {
|
||||
applyStackDecryptAndWipe(M, GV, CurId, EncGV, KeyGV, Raw.size(),
|
||||
LeafInsts, SeenFunctions, TouchedFunctions);
|
||||
Audit.StringsStackEncryptedCount++;
|
||||
} else {
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_str_", EncGV, KeyGV,
|
||||
BufGV, StateGV, BufGV, Raw.size(), Align(1));
|
||||
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/false,
|
||||
LeafInsts, SeenFunctions, TouchedFunctions);
|
||||
}
|
||||
|
||||
GV->removeDeadConstantUsers();
|
||||
if (GV->use_empty())
|
||||
GV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
LeafInsts.clear();
|
||||
bool MatchedSwift =
|
||||
!GV->use_empty() && Raw.size() >= 16 &&
|
||||
collectControlledUsersEx(
|
||||
GV, /*AllowSwiftBias=*/true,
|
||||
[&](const Function &F) {
|
||||
return Policy.shouldEncryptSwiftStringsInFunction(F);
|
||||
},
|
||||
LeafInsts);
|
||||
|
||||
if (MatchedSwift) {
|
||||
uint64_t CurId = NextId++;
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(8),
|
||||
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
|
||||
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_sw_", EncGV, KeyGV, BufGV,
|
||||
StateGV, BufGV, Raw.size(), Align(8));
|
||||
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/true, LeafInsts,
|
||||
SeenFunctions, TouchedFunctions);
|
||||
|
||||
GV->removeDeadConstantUsers();
|
||||
if (GV->use_empty())
|
||||
GV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Audit.SwiftStringsEncryptedCount++;
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!GV->use_empty())
|
||||
Audit.StringsSkippedCount++;
|
||||
}
|
||||
|
||||
for (const std::string &FnName : TouchedFunctions)
|
||||
Audit.StringsEncryptedFunctions.push_back(FnName);
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
Reference in New Issue
Block a user