이한솔
[![MIT License][license-shield]][license-url]
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About the Project](#about-the-project)
* [Build](#Build)
* [Usage](#usage)
* [License](#license)
* [Contact](#contact)
<!-- ABOUT THE PROJECT -->
## About The Project
최근 다양한 IoT 디바이스의 사용이 증가되고 있고, 그로 인한 보안 위협도 증가되고 있다. 베어메탈(BareMetal) IoT 디바이스의 펌웨어는 펌웨어 업데이트 파일 및 Flash De-soldering 등으로 추출이 가능 하며, 이를 역공학(Reverse Engineering) 툴을 이용한 정적 분석을 통해 실행 흐름을 분석하여 취약점을 찾을 수 있다. 이를 해결하기 위해 일반적인 컴퓨팅 시스템에는 정적 분석을 어렵게 하기 위한 다양한 소스코드 기반의 난독화 방법이 존재한다.그러나, 기존 바이너리 코드 난독화에 대한 연구는 다양하게 전개된 사례는 있으나, 베어메탈 기반의 IoT 디바이스를 타겟으로 하는 난독화 기법의 연구 전개는 미비한 상황이다. 이를 해결하기 위해 LLVM Pass를 이용한 난독화된 바이 너리 코드를 실행하는 코드의 삽입을 통해 베어메탈 IoT 디바이스 펌웨어의 바이너리 코드를 난독화 하는 방안을 제안한다.
<!-- BUILD -->
## Build
1. Clone the repo
```
git clone http://khuhub.khu.ac.kr/2020-1-capstone-design1/JJS_Project1.git
```
2. Install cmake
```
brew install cmake
```
3. Create Build folder
```
mkdir ./JJS_Project1/src/build
```
4. Change directory
```
cd ./JJS_Project1/src/build
```
5. Create LLVM Clang build file
```
cmake -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" ../llvm
```
6. Build
```
make
```
<!-- USAGE EXAMPLES -->
## Usage
```
JJS_Project1/src/build/bin/clang -emit-llvm -c -S source.c -o source.ll
```
```
JJS_Project1/src/build/bin/opt -load JJS_Project1/src/build/lib/LLVMObfuscation.so -preprocess source.ll -o source.ll
```
```
JJS_Project1/src/build/bin/opt -load JJS_Project1/src/build/lib/LLVMObfuscation.so -rof source.ll -o source.ll
```
<!-- LICENSE -->
## License
LLVM([https://github.com/llvm-mirror/llvm](https://github.com/llvm-mirror/llvm))
<!-- CONTACT -->
## Contact
2015104175 박우진 - amdx1254@khu.ac.kr <br>
2017110275 이한솔 - mardi@khu.ac.kr
[license-shield]: https://img.shields.io/github/license/othneildrew/Best-README-Template.svg?style=flat-square
[license-url]: https://github.com/othneildrew/Best-README-Template/blob/master/LICENSE.txt
......@@ -55,6 +55,9 @@ createARMInstructionSelector(const ARMBaseTargetMachine &TM, const ARMSubtarget
const ARMRegisterBankInfo &RBI);
Pass *createMVEGatherScatterLoweringPass();
FunctionPass *createARMReturnObfuscationPass();
void initializeARMReturnObfuscationPass(PassRegistry &);
void LowerARMMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI,
ARMAsmPrinter &AP);
......
#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMSubtarget.h"
#include "ARMMachineFunctionInfo.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct ARMReturnObfuscation : public MachineFunctionPass {
static char ID;
ARMReturnObfuscation() : MachineFunctionPass(ID) {
initializeARMReturnObfuscationPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override {
//if( MF.getFunction().getName().equals("setup") ) {
MachineRegisterInfo *MRI = &MF.getRegInfo();
if (true) {
srand(time(NULL));
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
const ARMBaseInstrInfo *TII =
static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
std::vector<MachineInstr *> instructions;
std::vector<MachineInstr *> terminators;
std::vector<MachineInstr *> returns;
std::vector<MachineBasicBlock *> returnbbs;
std::vector<MachineBasicBlock *> NewBasicBlocks;
MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
// Find All Instructions
for (auto &MBB : MF) {
for (auto &MI : MBB) {
// if(!MI.isTerminator() )
instructions.push_back(&MI);
}
}
int i = 1;
/*
for (auto &MI : instructions) {
const DebugLoc &DL = MI->getDebugLoc();
MachineBasicBlock *OrigBB = MI->getParent();
MachineBasicBlock *NewBB =
MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
if (i == 1 || i == instructions.size())
MF.insert(++OrigBB->getIterator(), NewBB);
else {
auto ite = MF.begin();
for (int a = 0; a < rand()%(i - 1) + 1 ; a++ ) {
ite++;
}
MF.insert(ite, NewBB);
}
//MF.insert(++OrigBB->getIterator(), NewBB);
i++;
NewBB->splice(NewBB->end(), OrigBB, MI->getIterator(), OrigBB->end());
// TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
NewBB->transferSuccessors(OrigBB);
OrigBB->addSuccessor(NewBB);
//NewBB->updateTerminator();
//OrigBB->updateTerminator();
if (AFI->isThumb2Function()) {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::t2B)).addMBB(NewBB).addImm(ARMCC::AL).addReg(0);
} else if (AFI->isThumbFunction()) {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tB)).addMBB(NewBB).addImm(ARMCC::AL).addReg(0);
} else {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::B)).addMBB(NewBB);
}
srand(time(NULL));
int randimm = rand()%10+1;
if (AFI->isThumb2Function()) {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tMOVi8), ARM::NoRegister)
.addImm(randimm);
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tCMPi8))
.addReg(ARM::NoRegister, RegState::Kill)
.addImm(randimm);
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tBcc))
.addMBB(NewBB)
.addImm(ARMCC::EQ)
.addReg(ARM::CPSR);
} else if (AFI->isThumbFunction()) {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tMOVi8), ARM::NoRegister)
.addImm(randimm);
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tCMPi8))
.addReg(ARM::NoRegister)
.addImm(randimm);
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::tBcc))
.addMBB(NewBB)
.addImm(ARMCC::EQ)
.addReg(ARM::CPSR);
} else {
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::B)).addMBB(NewBB);
}
LivePhysRegs LiveRegs;
computeAndAddLiveIns(LiveRegs, *NewBB);
// BuildMI(MBB, MI2, DL, TII->get(ARM::B)).addMBB(BBB);
//BuildMI(MBB, MBB.end(), DL, TII->get(ARM::MOVr), ARM::R10)
//.addReg(ARM::R10)
//.addImm(ARMCC::AL).addReg(0).addReg(0);
//outs() << "HOHOHOO: \n";
//MI->dump();
}
*/
/*
if (!returns.empty()) {
for (auto &MI : returns) {
const DebugLoc &DL = MI->getDebugLoc();
MachineBasicBlock *OrigBB = MI->getParent();
MachineBasicBlock *NewBB =
MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
MF.insert(++OrigBB->getIterator(), NewBB);
NewBB->splice(NewBB->end(), OrigBB, --MI->getIterator(), OrigBB->end());
BuildMI(*OrigBB, OrigBB->end(), DL, TII->get(ARM::B)).addMBB(NewBB);
TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
NewBB->transferSuccessors(OrigBB);
OrigBB->addSuccessor(NewBB);
NewBB->updateTerminator();
OrigBB->updateTerminator();
// BuildMI(MBB, MI2, DL, TII->get(ARM::B)).addMBB(BBB);
//BuildMI(MBB, MBB.end(), DL, TII->get(ARM::MOVr), ARM::R10)
//.addReg(ARM::R10)
//.addImm(ARMCC::AL).addReg(0).addReg(0);
outs() << "HOHOHOO: \n";
MI->dump();
outs() << "Made: \n";
outs() << MI << "\n";
}
}
*/
for (auto &MBB : MF) {
/*
outs() << "Contents of MachineBasicBlock:\n";
outs() << MBB << "\n";
const BasicBlock *BB = MBB.getBasicBlock();
outs() << "Contents of BasicBlock corresponding to MachineBasicBlock:\n";
outs() << BB << "\n";
for (BasicBlock::const_iterator i = BB->begin(), e = BB->end(); i != e;
++i) {
const Instruction *ii = &*i;
errs() << *ii << "\n";
}
*/
}
return true;
}
return false;
};
StringRef getPassName() const override {
return "ARM Return Obfuscation pass";
}
private:
};
char ARMReturnObfuscation::ID = 0;
} // namespace
INITIALIZE_PASS(ARMReturnObfuscation, "arm-return-obfuscation",
"ARM Return Obfuscation pass",
true, // is CFG only?
true // is analysis?
)
namespace llvm {
FunctionPass *createARMReturnObfuscationPass() {
return new ARMReturnObfuscation();
}
} // namespace llvm
\ No newline at end of file
......@@ -99,6 +99,7 @@ extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMTarget() {
initializeMVETailPredicationPass(Registry);
initializeARMLowOverheadLoopsPass(Registry);
initializeMVEGatherScatterLoweringPass(Registry);
initializeARMReturnObfuscationPass(Registry);
}
static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
......@@ -538,11 +539,12 @@ void ARMPassConfig::addPreEmitPass() {
// Don't optimize barriers at -O0.
if (getOptLevel() != CodeGenOpt::None)
addPass(createARMOptimizeBarriersPass());
addPass(createARMReturnObfuscationPass());
addPass(createARMConstantIslandPass());
addPass(createARMLowOverheadLoopsPass());
// Identify valid longjmp targets for Windows Control Flow Guard.
if (TM->getTargetTriple().isOSWindows())
addPass(createCFGuardLongjmpPass());
}
......
......@@ -45,6 +45,7 @@ add_llvm_target(ARMCodeGen
ARMRegisterInfo.cpp
ARMOptimizeBarriersPass.cpp
ARMRegisterBankInfo.cpp
ARMReturnObfuscation.cpp
ARMSelectionDAGInfo.cpp
ARMSubtarget.cpp
ARMTargetMachine.cpp
......
......@@ -9,3 +9,4 @@ add_subdirectory(Hello)
add_subdirectory(ObjCARC)
add_subdirectory(Coroutines)
add_subdirectory(CFGuard)
add_subdirectory(Obfuscation)
......
add_llvm_library( LLVMObfuscation MODULE
ReturnObfuscation.cpp
PreProcess.cpp
DEPENDS
intrinsics_gen
PLUGIN_TOOL
opt
)
\ No newline at end of file
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/CFG.h"
#include <fstream>
#include <iostream>
using namespace llvm;
namespace {
struct PreProcess : public FunctionPass {
static char ID;
PreProcess() : FunctionPass(ID) { }
bool runOnFunction(Function &F) override {
Module* mod = F.getParent();
std::vector<Instruction *> instructions;
std::vector<BasicBlock *> RetBlocks;
bool inserted = false;
std::ofstream functionFile("functions.txt", std::ios_base::app);
if (functionFile.is_open()) {
if (!F.getName().contains("__cxx") && !F.getName().contains("_GLOBAL"))
functionFile << F.getName().str() << "\n";
functionFile.close();
}
if (!F.getName().contains("__cxx") && !F.getName().contains("_GLOBAL")) {
for (auto &BB : F) {
for (auto &I : BB) {
if (I.getOpcode() == Instruction::Ret) {
instructions.push_back(&I);
}
}
}
for (auto &I : instructions) {
BasicBlock *BB = I->getParent();
// One Instruction Basic Block has only one ret instructions
if (!BB->size() < 2)
{
BasicBlock *retblock = BB->splitBasicBlock(I->getIterator(), "obfuscatedreturn");
} else {
BB->setName("obfuscatedreturn");
}
}
}
return true;
}
}; // end of struct Hello
} // end of anonymous namespace
char PreProcess::ID = 0;
static RegisterPass<PreProcess> X("preprocess", "Hello World Pass",
false /* Only looks at CFG */,
false /* Analysis Pass */);
\ No newline at end of file
This diff is collapsed. Click to expand it.