Character string obfuscation technology application design a character string obfuscation program can confuse strings in. Net assembly

Source: Internet
Author: User
Tags mscorlib

There are currently two articles on string research.

Principles: Application of string obfuscation Technology in. Net Program protection and how to decrypt obfuscated strings

Practice: String anti-obfuscation practices dotfuscator 4.9 string encryption technology Countermeasures

The third article is about how to apply the content learned above and design a string obfuscation program.

First, design a console program, which is the Assembly file to be obfuscated by me:

public static void Main(){        try        {            RunSnippet();        }        catch (Exception e)        {            string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());            Console.WriteLine(error);        }        finally        {            Console.Write("Press any key to continue...");            Console.ReadKey();        }}
 

The Code is the standard template of snippet compiler. Print a string on the console. Here, there are two string constants, which are the places where I need to encrypt them.

You cannot directly change the source code, and you must operate the Assembly as a program. To modify the. NET assembly, you can now find mono. Cecil, and the latest version is 0.9.5.0.

First, design the obfuscation algorithm, which is a very simple base64 code conversion. This step can be further explored to create more complex obfuscation algorithms.

public static string StringDecode(string text1){    return Encoding.UTF8.GetString(Convert.FromBase64String(text1));}

To convert this code into il code, use mono. Cecil to inject it into the set of programs. Let's first look at the code translated into Il.

.method public hidebysig static string StringDecode(string) cil managed{    .maxstack 8    L_0000: call class [mscorlib]System.Text.Encoding [mscorlib]System.Text.Encoding::get_UTF8()    L_0005: ldarg.0     L_0006: call uint8[] [mscorlib]System.Convert::FromBase64String(string)    L_000b: callvirt instance string [mscorlib]System.Text.Encoding::GetString(uint8[])    L_0010: ret }

Compare the mono. Cecil syntax example and translate the above il code into C # code.

MethodDefinition new_method = new MethodDefinition("StringDecode", attr, asm.MainModule.Import(typeof(string)));ParameterDefinition para = new ParameterDefinition(asm.MainModule.Import(typeof(string)));new_method.Parameters.Add(para);tp.Methods.Add(new_method);new_method.Body.MaxStackSize = 8;MethodReference mr;ILProcessor worker = new_method.Body.GetILProcessor ();mr = asm.MainModule.Import(typeof(Encoding).GetMethod("get_UTF8"));worker.Append(worker.Create(OpCodes.Call, mr));worker.Append(worker.Create(OpCodes.Ldarg_0));mr = asm.MainModule.Import(typeof(Convert).GetMethod("FromBase64String"));worker.Append(worker.Create(OpCodes.Call, mr));mr = asm.MainModule.Import(typeof(Encoding).GetMethod("GetString", new Type[] { typeof(Byte[]) }));worker.Append(worker.Create(OpCodes.Callvirt, mr));worker.Append(worker.Create(OpCodes.Ret));

 

Again, I want to search all the strings in the target assembly and convert them into base64 string encoding, So I traverse the Il command and convert it.

List<Instruction>  actionInsert=new List<Instruction> ();foreach (Instruction ins in entry_point.Body.Instructions){       if (ins.OpCode.Name == "ldstr")       {                Console.WriteLine("Find target instruction, start modify..");                byte[] bytes = System.Text.Encoding.UTF8.GetBytes (Convert.ToString (ins.Operand));                ins.Operand = Convert.ToBase64String (bytes);                                    actionInsert.Add(ins);      }
}
 
 

Finally, we replace the original command with a string obfuscation algorithm call.

for (int i = 0; i < actionInsert.Count; i++){         mr = asm.MainModule.Import(new_method);         worker = entry_point.Body.GetILProcessor();         worker.InsertAfter(actionInsert[i], worker.Create(OpCodes.Call, mr));}
 
 

Finally, save the Assembly and load the Assembly with. Net reflector, as shown in, the string constant has become a method call:

This increases the difficulty of code decompilation. The meaning of a string is completely replaced with a bunch of meaningless strings.

In the latest mono. Cecil version, the API changes. The read assembly and write assembly applied in this program code

string path = @"C:\Users\Administrator\Desktop\CPP\Default.exe";AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(path);MethodDefinition entry_point = asm.EntryPoint;path = @"C:\Users\Administrator\Desktop\CPP\DefaultSecury.exe";asm.MainModule.Write(path);

For the string obfuscation algorithm, the following lists several obfuscation algorithms that I have found. The encryption intensity is higher:

static string stringEncrypt(string string_0){    char[] chArray;    char[] chArray1 = chArray = string_0.ToCharArray();    while (true)    {        int num;        int length = chArray1.Length;        if (length <= 0)        {            break;        }        chArray1[num = length + -1] = (char) (chArray[num] - 'ᑩ');    }    return string.Intern(new string(chArray));}
 

The following is the obfuscation algorithm of dotfuscator. It also adds salt, which improves the strength a lot.

static string GetString(string source, int salt) {     int index = 0;     char[] data = source.ToCharArray();     salt += 0xe74d6d7; // This const data generated by dotfuscator     while (index < data.Length)     {         char key = data[index];         byte low = (byte)((key & '\x00ff') ^ salt++);         byte high = (byte)((key >> 8) ^ salt++);         data[index] = (char)((low << 8 | high));         index++;     }     return string.Intern(new string(data)); }
 

After obfuscated strings, the meaning of the original text is completely invisible. For example, the following code snippets have some doubts about the character set it uses, a bit like the languages of the Middle East countries.

 

Let's take a look at an example with Chinese characters in the Code. This is a piece of user login code, and its encrypted characters seem more incomprehensible.

To mix strings with salt, simply modify the above Code, add a temporary variable, and then add it to the called obfuscation algorithm.

The full-text code is written in nunit testing. unit testing and resharper are really easy to use, saving a lot of code. One method can be started and run as an entry program.

It brings a lot of convenience to development and testing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.