0% found this document useful (0 votes)
903 views5 pages

(C#) Mini String Obfuscator - Protect Strings - Mono

This document discusses using Mono.Cecil to obfuscate strings in a .NET application. It describes Mono.Cecil as a library for analyzing and modifying .NET binaries. The author creates a simple program with unencrypted strings and then uses Mono.Cecil to find all strings, encrypt them using Base64 encoding, and inject a decryption method to decrypt the strings at runtime. This provides a proof of concept for basic string obfuscation. Later comments discuss alternatives like dnlib and how emulation in tools like de4dot could still decrypt the strings.

Uploaded by

rhizom cruz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
903 views5 pages

(C#) Mini String Obfuscator - Protect Strings - Mono

This document discusses using Mono.Cecil to obfuscate strings in a .NET application. It describes Mono.Cecil as a library for analyzing and modifying .NET binaries. The author creates a simple program with unencrypted strings and then uses Mono.Cecil to find all strings, encrypt them using Base64 encoding, and inject a decryption method to decrypt the strings at runtime. This provides a proof of concept for basic string obfuscation. Later comments discuss alternatives like dnlib and how emulation in tools like de4dot could still decrypt the strings.

Uploaded by

rhizom cruz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy