Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / XML
Article

Code Security in .NET

Rate me:
Please Sign up or sign in to vote.
4.07/5 (37 votes)
16 Aug 2008CPOL7 min read 388.5K   1.7K   96   29
All about vulnerabilities with Code Reverse Engineering, and the best steps to fix them (DotFuscator included).

Introduction

Security is one of the most primary concerns for everyone in IT. When we talk about security, we generally think about Data Security. Data is the most important part of every company. We secure data so that unethical minds cannot break through the security gates and get valuable information. In IT, it is common to store information securely. Thus, we use databases to store data than files as to tighten the security of data. To connect to a database, we need ConnectionStrings, which securely connect the database and fetch data. These connection strings are stored in configuration files, and for additional security, we use encryption algorithms to encrypt our data so that no human being can understand our data.

To implement security, .NET provides some superior classes. The classes within the System.Security namespace provide a superior quality library that enhances the security of any application.

But, one thing that never comes to our mind is the security of code. Code security is generally more important than data security. Generally, when we are dealing with .NET assemblies, we write all the security techniques inside it, use our security classes from the code, or even write crypto keys within the business logic.

As we all know, .NET is a framework that produces aseemblies, which are just similar to Assembly Language code which is understood by the CLR (JIT). Thus, the Assembly code is compiled during runtime. Therefore, any assembly editor can pass through this gate and discover your business logic easily.

Background

In the case of traditional machine languages, they are very hard to understand as they are written in binary. But, .NET assemblies are not. Any good programmer or even a newbie can get your business logic from an assembly provided.

This would facilitate the programmers to reverse engineer the assemblies and get the actual code from it. Thus, any business logic that you have written for your application could easily be open to all. Even if you have made use of superior quality security measures to encrypt all the data access, it will be very easy to get into those by reverse engineering your code.

There are some readily available Code Generators that can produce almost the exact code that is used to produce an assembly. For example, we can use the Reflector, which is free to download, and can produce C#, VB.NET, C++, or DELPHI code from our assembly.

In the following demo, I am going to use Lutz Roeder's Reflector project to disassemble a Class Library, and later, we will explain how to avoid this problem. Get Lutz Roeder's Reflector from here. If it is not found there, try this: Download Lutz Roeder's Reflector - 1.04 MB.

Problems with .NET Assemblies

Let's start building a simple class library. Let the code of the assembly be like this:

C#
using System; 
using System.Collections.Generic;
using System.Text;

namespace MyFixedLibrary
{
    public class LibraryClass
    {
        /// <summary>
        /// MethodFromFixedLibrary Comments
        /// </summary>
        public void MethodFromMyFixedLibrary()
        {
            int myidentifier = 10; 
            string myString = "This is a String";
            for(int i=0;i<myidentifier;i++)
                Console.Write(myString);
        }         
    } 
}

This is a simple code that introduces the MyFixedLibrary namespace, and within it, there is a class called LibraryClass. The LibraryClass has a method called MethodFromFixedLibrary.

fixeddemo.JPG

Now, take a closer look at the name of the identifiers. The first identifier is myIdentifier and the second one is myString. Generally, we make identifiers in such a way that it is clearly understood what the identifier will be doing in the current context.

After building the class library, it produces a DLL. Upon loading the DLL in Lutz's Reflector, it produces the exact code by its reverse engineer logic. Take a look at the picture below:

fixeddemo1.JPG

This is really a threat to development teams. There are some add-ins provided with the disassembler which will produce the exact solution that made up the DLL. Thus, it must be clear how a disassembler can be used to get your precious code from your .NET assemblies.

Try it yourself.

How to Solve this Problem?

To solve this problem, we have to do two steps:

  1. After installation of your software, you can use NGen to run, which will produce the native machine code and force the DLLs to convert to binary.
  2. Use the DotFuscator and the Obfuscation tool that comes with Visual Studio .NET.

1. NGEN

To use NGEN, you must write a special code that would optimize your code to machine language and add it as post-installation code. You must also ship ngen.exe with your application. If you have a big application, the optimization code will take too long to convert the DLLs to machine specific code. This would bore the users.

Note: You can also add DLLs that are already native generated. But, this will cause the DLL to run only on your platform. Means, if you optimized the DLL in Win XP, it may cause problems in Vista or other Operating Systems. So, it is always a good practice to create machine code from your installation application.

To read more about NGEN, try MSDN.

2. DotFuscator

We may also take the help of Obfuscatory tools to compile the DLL so that the logic could be made hard to understand. In this section, I am going to demonstrate how to use DotFuscator to reach your goal. Here are the steps:

  1. First, after you have made the library, you need to open DotFuscator. Go to Start-Programs->Visual Studio .NET -> Visual Studio Tools->Dotfuscator Community Edition.
  2. Note: This is Community Edition and comes free with Visual Studio .NET. You can easily buy the Premium Edition and get all the facilities.

  3. After opening the assembly, you need to configure it so that the assembly could be obfuscated. In the figure below, choose the Setup tab to be used for the settings. Configdir is the place where the output DLL will be saved.

dotfuscator1.JPG

  1. In the next Options tab, for community edition, there is only one, option which is readonly. If Disable Renaming is set to No, it means the variables and private functions will be renamed in such a way that it would be hard to understand the logic.

dotfuscator2.JPG

  1. In the Input tab, choose Library to make the assembly a library project. You can also choose Honor Obfuscation Attributes, or Strip Obfuscation Attributes. These are optional.

dotfuscator3.JPG

  1. In the Rename tab, you will have to choose Map.xml which provides DLL mapping. If additional DLLs are needed, you can store the info into the XML file.

dotfuscator4.JPG

  1. The Build tab will help you to set the output directory.

dotfuscator5.JPG

Note: Regarding the other tabs, they are not available for Community Editions. They are only available with the Premium editions.

Thus, after obfuscation, the code will look like:

fixeddemo2.JPG

C#
using System; 
using System.Collections.Generic;
using System.Text;

namespace MyFixedLibrary
{
    public class LibraryClass
    {
        /// <summary>
        /// MethodFromFixedLibrary Comments
        /// </summary>
        public void MethodFromMyFixedLibrary()
        {
            int num= 10; 
            string str = "This is a String";
            for(int i=0;i<num;i++)
                Console.Write(str);
        }         
    } 
}

The method name remains the same, but all the private variables have been renamed. You can see that num has been mapped to myidentifier and str has been mapped to mystring.

Therefore, if your assembly is very big, making changes to the variables will make it hard for the disassembler.

Another thing, the Community Edition does not provide much facilities. In the full version of the DotFuscator, the obfuscation will be extensive. It can rename your namespaces, and even strings.

Additional Info (Include DotFuscator as a Post Build Event)

You may also add obfuscation as a Post Build Custom Event of your project. To do this, you need to create a project file, which is an XML document that will look like the sample given below:

XML
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE dotfuscator SYSTEM 
    "http://www.preemptive.com/dotfuscator/dtd/dotfuscator_v2.1.dtd">
<dotfuscator version="2.1">
  <!--This is application generated code. Do not edit manually.-->
  <global />
  <input>
    <asmlist>
      <inputassembly>
        <option>library</option>
        <file dir="C:\MyFixedLibrary\bin\Debug" name="MyFixedLibrary.dll" />
      </inputassembly>
    </asmlist>
  </input>
  <output>
    <file dir="C:\ObfuscatedDlls" />
  </output>
  <tempdir>
    <file dir="C:\tempdir" />
  </tempdir>
  <renaming>
    <mapping>
      <mapoutput overwrite="false">
        <file dir="C:\Mapdir" name="map.xml" />
      </mapoutput>
    </mapping>
  </renaming>
</dotfuscator>

This XML file is produced automatically whenever you create a project in DotFuscator. Here, the InputAssembly will hold the input file assembly which should be your project directory, Bin/Debug or bin/Release, where the output of the build will be stored. The output directory is where the final DLL which is produced is available after obfuscation. The Map.xml file from MapDir is another XML file which would be created automatically and used for logging everything that the DotFuscator has done with your DLL. From this file, you would get information regarding all the functions and variable name changes that the process has made.

Now, to include the event: go to Project - > Properties->Build Events, and add these lines to the post build event:

C:\Program Files\PreEmptive Solutions\Dotfuscator 
   Community Edition 1.1\dotfuscator.exe" /q c:\dproj\demo.xml

postbuildevent.JPG

Please change the Dotfuscator file path and the project path where you have created your project.

History

This is the first version of this article. Hope you will like my article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
GeneralMy vote of 5 Pin
Darrell Ulm19-Jun-20 4:02
Darrell Ulm19-Jun-20 4:02 
QuestionProblem while using dotfuscator to fuscate my exe file Pin
srilekhamenon25-Apr-16 21:53
professionalsrilekhamenon25-Apr-16 21:53 
AnswerRe: Problem while using dotfuscator to fuscate my exe file Pin
Abhishek Sur26-Apr-16 21:49
professionalAbhishek Sur26-Apr-16 21:49 
GeneralRe: Problem while using dotfuscator to fuscate my exe file Pin
srilekhamenon29-Apr-16 0:55
professionalsrilekhamenon29-Apr-16 0:55 
QuestionPlease give some more info about your last step, where and what etc has to be included etc Pin
Mohiyuddin Khan27-May-14 5:46
Mohiyuddin Khan27-May-14 5:46 
hi Abhi

Please give some more info about your last step, where and what etc has to be included etc.

In project these lines i have to included, the project where the exe is build or in the project where i am doing the setup file or in the project DotFuscator exe i am making.

Please give some more info as i have tried without this last step but after installing the application it is giving error. when i have debug it, it is asking for proper path of assemblies etc etc. Error code is:
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "RailwayStationCarBooking.Properties.Resources.resources" was correctly embedded or linked into assembly "RailwayStationCarBooking-01" at compile time, or that all the satellite assemblies required are loadable and fully signed.
Khan

GeneralMy vote of 5 Pin
Sandesh M Patil29-Dec-10 4:55
Sandesh M Patil29-Dec-10 4:55 
GeneralMy vote of 5 Pin
GarlicBoris24-Oct-10 21:32
GarlicBoris24-Oct-10 21:32 
GeneralMy vote of 5 Pin
GPUToaster™11-Aug-10 23:41
GPUToaster™11-Aug-10 23:41 
GeneralDamaged exe Pin
Muammar©28-Nov-09 22:53
Muammar©28-Nov-09 22:53 
GeneralRe: Damaged exe Pin
Muammar©1-Dec-09 0:40
Muammar©1-Dec-09 0:40 
GeneralFantastic Pin
ranjan_namitaputra2-Oct-09 11:20
ranjan_namitaputra2-Oct-09 11:20 
GeneralRe: Fantastic Pin
Abhishek Sur5-Nov-09 6:54
professionalAbhishek Sur5-Nov-09 6:54 
GeneralReally very powerful for data and code security Pin
Anubhava Dimri9-Sep-09 23:52
Anubhava Dimri9-Sep-09 23:52 
GeneralRe: Really very powerful for data and code security Pin
Abhishek Sur10-Sep-09 0:42
professionalAbhishek Sur10-Sep-09 0:42 
GeneralClear concise and best Pin
Ashutosh Phoujdar22-Jan-09 21:22
Ashutosh Phoujdar22-Jan-09 21:22 
JokeBest VB.NET article of August 2008 Pin
Bill Boukouvalas10-Oct-08 1:18
Bill Boukouvalas10-Oct-08 1:18 
GeneralRe: Best VB.NET article of August 2008 Pin
Abhishek Sur11-Oct-08 6:25
professionalAbhishek Sur11-Oct-08 6:25 
GeneralRe: Best VB.NET article of August 2008 Pin
Bill Boukouvalas12-Oct-08 23:26
Bill Boukouvalas12-Oct-08 23:26 
GeneralCongratulation Pin
Abhijit Jana30-Sep-08 1:40
professionalAbhijit Jana30-Sep-08 1:40 
GeneralRe: Congratulation Pin
Abhishek Sur7-Oct-08 8:07
professionalAbhishek Sur7-Oct-08 8:07 
GeneralObfuscated Items Pin
GLLNS21-Sep-08 12:59
GLLNS21-Sep-08 12:59 
GeneralRe: Obfuscated Items Pin
Abhishek Sur2-Oct-08 21:49
professionalAbhishek Sur2-Oct-08 21:49 
Generalone more times Pin
Abhijit Jana7-Sep-08 19:57
professionalAbhijit Jana7-Sep-08 19:57 
GeneralNice one Pin
Abhijit Jana18-Aug-08 17:52
professionalAbhijit Jana18-Aug-08 17:52 
GeneralRe: Nice one Pin
Abhishek Sur18-Aug-08 21:04
professionalAbhishek Sur18-Aug-08 21:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.