Anda di halaman 1dari 5

30/7/2015

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion
+HackForums(http://www.hackforums.net)
+Forum:Programming,Coding,andLanguages(/forumdisplay.php?fid=151)
+Forum:VisualBasicand.NETFramework(/forumdisplay.php?fid=118)
+Forum:C#ProgrammingLanguage(/forumdisplay.php?fid=208)
+Thread:[C#]MiniStringObfuscatorProtectStrings|Mono.Cecil(/showthread.php?tid=4733906)

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilGhostCode0316201503:57PM

MiniStringObfuscator
WhatisMono.Cecil?
InthefollowingtutorialIamgoingtoexplainhowyoucancodeyourown
tinystringobfuscatorwithMono.Cecil.
Mono.CecilwascreatedbyjbevainandisanopensourceprojectavailableonGitHub
Mono.CecilisalibrarytogenerateandinspectprogramsandlibrariesintheECMACILform.
Toputitsimply,youcanuseCecilto:
Analyze.NETbinariesusingasimpleandpowerfulobjectmodel,withouthavingtoloadassembliestouse
Reflection.
Modify.NETbinaries,addnewmetadatastructuresandaltertheILcode.
Sowiththislibweareabletomodify.netprograms,aftertheyhavebeencompiledintoaexecutable.
Thelibisverypowerfulandcandoalotofstuff.
TodayIamgoingtoexplainhowitcanbeusedtoencrypt/encodethestringinyour.netprogram.

Stringsina.Netassembly
Todothiswearegoingtocreateasmalltestapplication:

Thestringsofthisapplicationwearegoingtosecure.
AtthecurrentstateallthestringscanbeseenaftercompilationbyusingadecompilerlikeIlSpy/SAE/Reflector.

Ifwethinkofthesestringsbeingapassword/passkeyahackerwouldhaveaneasyjobjustbyfindingoutthe
passwordusingadecompiler.
Ifweencryptthisstringitbecomeshardertofindoutthekey.
Sowhatwewanttodoisencryptthestringanddecryptitonruntime.
AndthatswhatweareusingMono.Cecilfor.

http://www.hackforums.net/printthread.php?tid=4733906

1/5

30/7/2015

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion

GettingStarted
DownloadMono.CecilfromGitHubandcompilethedllfile.
NowcreateanewconsoleapplicationinvisualstudioandaddMono.Cecil.dllasareference.
Makesuretoaddtheseimports:
Code:
usingMono.Cecil;
usingMono.Cecil.Cil;
Onceagain,whatwehaveatthemomentinthetargetassemblyissomethinglikethis:
ldstr"Hello"
CallConsole.WriteLine(System.String)
Butwhatwewanttogetisthis:
ldstr"EncryptedString"
CallDecryptFunction()
CallConsole.WriteLine(System.String)
Sowhatweneedtodois:
1.
2.
3.
4.

Findallstrings(ldstr)inourtargetassembly.
Changethestringtoanencryptedstring
Injectamethodwhichperformsthedecryption
Callthedecryptionmethodafterourstringgotpushedtothestack

Addthisfunctiontoyourproject:
Code:
publicstaticstringEncode(stringstr)
{
returnConvert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str));
}
ItsbasicllyBase64encryptingastring.
ThisisnotaverystrongencryptionbutyoucaneasilychangethistoAES/RSAetc.
Forthesakeofthistutorialitshouldbealright.
NextwhatweaddtoourMain()methodisthis:
Code:
AssemblyDefinitionAssemblyDef=AssemblyDefinition.ReadAssembly(@"C:\Users\Admin\Desktop\MyFile.exe");
Thisloadsourtargetfileweliketosecure.
Nowyourprojectshouldlooklikethis:

Injectingthedecrypter
Nowweneedtoinjectadecryptmethod(OurdecodeBasic64method)intoourtargetassembly.
Todothisyoucanusethisfunction:
Code:
privatestaticMethodDefinitionInjectDecrypter(AssemblyDefinitionAssemblyDef)
{
foreach(ModuleDefinitionModuleDefinAssemblyDef.Modules)
http://www.hackforums.net/printthread.php?tid=4733906

2/5

30/7/2015

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion

{
foreach(TypeDefinitionTypeDefinModuleDef.GetTypes())
{
if(TypeDef.Name=="<Module>")
{
MethodDefinitionMethodDef=CreateDecrypter(AssemblyDef);
TypeDef.Methods.Add(MethodDef);
returnMethodDef;
}
}
}
thrownewException("Decrypternotinjected.");
}
privatestaticMethodDefinitionCreateDecrypter(AssemblyDefinitionAssemblyDef)
{
MethodDefinitionDecrypt=newMethodDefinition("Decrypt",MethodAttributes.Public|
MethodAttributes.Static,AssemblyDef.MainModule.Import(typeof(string)));
Decrypt.Parameters.Add(newParameterDefinition(AssemblyDef.MainModule.Import(typeof(string))));
List<Instruction>Body=newList<Instruction>();
Body.Add(Instruction.Create(OpCodes.Call,
AssemblyDef.MainModule.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8"))));
Body.Add(Instruction.Create(OpCodes.Ldarg_0));
Body.Add(Instruction.Create(OpCodes.Call,
AssemblyDef.MainModule.Import(typeof(System.Convert).GetMethod("FromBase64String",newType[]{typeof(string)
}))));
Body.Add(Instruction.Create(OpCodes.Callvirt,
AssemblyDef.MainModule.Import(typeof(System.Text.Encoding).GetMethod("GetString",newType[]{typeof(byte[])
}))));
Body.Add(Instruction.Create(OpCodes.Ret));
foreach(InstructionInstrinBody)
{
Decrypt.Body.Instructions.Add(Instr);
}
returnDecrypt;
}
WearerebuildingaBase64Decodemethodbyhand.
Thismethodwearegoingtoinject:
Code:
MethodDefinitionMD=InjectDecrypter(AssemblyDef);

Encryptingourstrings
Nowweliketopeekintotheassemblyandfindallstrings.
TodothatweneedtoiteratethroughallModules,TypesMethods.
Wecandothislikethat:
Code:
foreach(ModuleDefinitionModuleDefinAssemblyDef.Modules)
{
foreach(TypeDefinitionTypeDefinModuleDef.GetTypes())
{
foreach(MethodDefinitionMethodDefinTypeDef.Methods)
{
}
}
}
NowweneedtolookintoallInstructionsinourMethod.
Beforewedothatweshouldmakesureourmethodhasabody,thenwecancontinue.
Code:
if(MethodDef.HasBody)
NowletsiteratethroughallInstructionsandfilterouttheLdstrInstructions(Strings).
WeencryptthesestringswithBase64,andreferenceourdecryptmethodaftertheencryptedstring,soitwillget
decryptedonruntime.
Code:
ILProcessorilp=MethodDef.Body.GetILProcessor();
http://www.hackforums.net/printthread.php?tid=4733906

3/5

30/7/2015

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion

for(inti=0;i<MethodDef.Body.Instructions.Count;i++)
{
InstructionInstructionDef=MethodDef.Body.Instructions[i];
if(InstructionDef.OpCode==OpCodes.Ldstr)
{
InstructionDef.Operand=Encode(InstructionDef.Operand.ToString());
ilp.InsertAfter(InstructionDef,Instruction.Create(OpCodes.Call,MD));
}
}

Writingthesecuredapplication
Nowwesaveourchangesbyjusttypingthis:
Code:
AssemblyDef.Write(@"C:\Users\Admin\Desktop\Secured.exe");

Thefinalcheck
Ifwenowopenupourapplciationwithadecompiler,wewillseethis:

Allstringshavebeenencoded.
Andifwestarttheappitworksjustfine!
Ifyouplantochangetheencryptionmethod(whichishighlyrecommended)makesuretorebuildtheDecrypterMethod
correctly.
YoucanuseadecompilertogetthecorrectMSILsoyouknowwhatInstructionstoaddtothemethodbody.
Ihopethistutorialwashelpfulforyouguys,pleasegivemesomefeedback.

*Only30316201504:09PM
wellexplainedformoreadvancedhttp://www.hackforums.net/showthread.php?tid=3883739
*GhostCode0316201504:13PM
Thanks.
Alsoanotherlibcalled'dnlib'isprettygood(ifnotbetter)fordoingthis.
FromwhatIknowdnlibalsosupportseditinghardlyobfuscatedassemblies,whileMono.Cecilmightfailonthose.
FurthermoreIliketoaddthatthisisjustaproofofconcept^^
*Only30316201504:24PM
hestartwithmonoandswitchtodnlibhepostdnlibstringexamplecheckhisthreads
*Mr.Trvp0316201505:23PM
(0316201504:13PM)GhostCodeWrote:Thanks.
Alsoanotherlibcalled'dnlib'isprettygood(ifnotbetter)fordoingthis.
FromwhatIknowdnlibalsosupportseditinghardlyobfuscatedassemblies,whileMono.Cecilmightfailon
those.
FurthermoreIliketoaddthatthisisjustaproofofconcept^^
ConfuserExandmanyotherapplicationsusednlib.Iwouldn'tbesurprisedofAppfuscatorusedit.

http://www.hackforums.net/printthread.php?tid=4733906

4/5

30/7/2015

[C#]MiniStringObfuscatorProtectStrings|Mono.CecilPrintableVersion

*GhostCode0317201512:42AM
Yes,thatiscorrect.
AndAppfuscatorisindeedbasedindnlib.
*LaPanthere0317201512:43AM
Honestlyitsnotgreat,butitshowswhatMono.Cecilcanbeusedfor.
Withyourstringencryption,itsassimpleasrunningde4dotonitinemulationstringdecryptionmodeandhaveit
removed.
WhetherornotyouuseMono.Cecilordnlib,itdoesn'treallybotherme.IMObotharequitereasonable,butdnlibhasan
advantageinmetadataediting.
*GhostCode0317201512:53AM
Hey:)
Yes,itshowswhatthoselibscanbeusedfor.
Ofcourseitspossibletodeobfuscatethiswithde4dotbyjustemulatingthedecryptionmethod,Iamwellawareofthat.
Buttherearequietafewtrickstopreventde4dotfromautomaticallydeobfuscatingthestrings.
Onewaywouldbetouseakeybasedencryptionalgorithmandmutatethekeyusedfordecryption,since
themutationengineofde4dot(default)hasquietafewproblemswithmutatedconstants.
YoucannoticethatifyoutrytodeobfuscatethestringsobfuscatedbyAppfuscator.
FurthermoreImentionedthatthisBase64isjustanexample,thereshouldbeuseddifferentencryptionsobviously.
Ijustdidn'twanttobuildanAESmethodbodybyhand..
*N3w8i3H4ck3r0317201505:22AM
AretherewrappersforVBbecauseiunderstanditmoreandjuststartedtotransitionontoc#
*GhostCode0317201505:28AM
Wrappers?
YoucanjustrecodewhatIexplainedabovewithVB.Net.Thatshouldn'tbehard.
Mono.CecilworksinC#aswellasinVB.Net.
IfyoustillhaveproblemstoconvertthatcodefromC#toVB.Netyoucanalways
useanonlineconverterorcompiletherelevantfunctionsasa*.dllandreferenceitinyourproject

http://www.hackforums.net/printthread.php?tid=4733906

5/5

Anda mungkin juga menyukai