You are on page 1of 120

1

Babel
Obfuscator
User’s Guide

Version 5.6.0.0
2

Babel Obfuscator User’s Guide

Manual Version 5.6.0.0


http://www.babelfor.net/

babelfor.NET
Copyright © 2011-2012 babelfor.NET. All rights reserved.

Trademarks
.NETTM , MSILTM, and Visual Studio .NETTM are trademarks of Microsoft, Inc.

All other trademarks are the property of their respective owners.

Warning and Disclaimer


Every effort has been made to make this manual as complete and accurate as possible, but no warranty or
fitness is implied. The information provided is on an “as is” basis. The author shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information
contained in this manual.
3
4

Table of Contents
Babel Obfuscator .......................................................................................................................................................... 1
User’s Guide ................................................................................................................................................................. 1
Trademarks .................................................................................................................................................................. 2
Warning and Disclaimer ............................................................................................................................................... 2
Table of Contents ............................................................................................................................................................. 4
Conventions Used in This Manual .................................................................................................................................. 10
Introduction ................................................................................................................................................................11
Obfuscation at Glance .................................................................................................................................................... 11
Benefits of Babel Obfuscator.......................................................................................................................................... 11
Software Requirements.................................................................................................................................................. 12
What’s New .................................................................................................................................................................... 13
Babel 5.6.0.0 changes ................................................................................................................................................ 13
Release Notes ................................................................................................................................................................. 13
Assembly version 5.6.0.0, File version 5.6.0.0 ........................................................................................................... 13
Babel Features .............................................................................................................................................................14
Product Features ............................................................................................................................................................ 15
General Features ........................................................................................................................................................ 15
Obfuscation ................................................................................................................................................................ 15
Code Protection ......................................................................................................................................................... 15
Code Instrumentation and Optimization ................................................................................................................... 15
Deployment................................................................................................................................................................ 15
Feature Matrix ................................................................................................................................................................ 17
Technology Matrix .......................................................................................................................................................... 19
Licensing ......................................................................................................................................................................... 20
Standard Licensing ..................................................................................................................................................... 20
Professional Licensing ................................................................................................................................................ 20
Enterprise Licensing ................................................................................................................................................... 21
Standard, Professional and Enterprise Additional Benefits ....................................................................................... 21
Licensing FAQ ................................................................................................................................................................. 22
License File ..................................................................................................................................................................... 22
Babel Obfuscator Version History .................................................................................................................................. 23
Latest Babel Obfuscator Commercial Version ................................................................................................................ 23
The Free Babel Obfuscator Version 2.0.0.1 .................................................................................................................... 23
Overview ........................................................................................................................................................................ 24
5

Starting Using Babel Obfuscator ..................................................................................................................................25


Setup .............................................................................................................................................................................. 26
Babel Obfuscator User Interface .................................................................................................................................... 27
Creating a New Solution File ...................................................................................................................................... 28
Load the Primary Source Assembly ............................................................................................................................ 28
Changing Obfuscation Settings .................................................................................................................................. 30
Code Generation Options .......................................................................................................................................... 30
Setting the Output and Building the Project .............................................................................................................. 31
Examine the Obfuscated Assemblies ......................................................................................................................... 32
Deobfuscating Stack Trace ......................................................................................................................................... 33
Launching Babel from Command Line............................................................................................................................ 34
Miscellaneous ................................................................................................................................................................. 34
--help [option] (?) ....................................................................................................................................................... 34
--[no]logo (enabled) ............................................................................................................................................. 35
--license ...................................................................................................................................................................... 35
--verbose <n> (v) ........................................................................................................................................................ 35
--noconfig (@) (disabled) ........................................................................................................................................ 35
--nowarn <warn list> .................................................................................................................................................. 35
--[no]warnaserror [warn list] ..................................................................................................................................... 36
--[no]statistics (enabled) ........................................................................................................................................ 36
--[no]agent (a) (enabled) ........................................................................................................................................ 36
--[no]satellite [assembly] ........................................................................................................................................... 36
--addsearch <path> .................................................................................................................................................... 36
--take <regex> ............................................................................................................................................................ 36
--skip <regex> ............................................................................................................................................................. 36
--compress <n> (6) .................................................................................................................................................. 36
--quickrule <rule> ....................................................................................................................................................... 37
Merge and Embed Assemblies ....................................................................................................................................... 37
--[no]internalize (disabled) .................................................................................................................................... 37
--[no]copyattrs (enabled) ....................................................................................................................................... 38
--embed <assembly> .................................................................................................................................................. 38
Renaming........................................................................................................................................................................ 38
--[no]types (t) (enabled) ......................................................................................................................................... 38
--[no]events (e) (enabled)....................................................................................................................................... 38
--[no]methods (m) (enabled) .................................................................................................................................. 38
--[no]properties (p) (enabled) ................................................................................................................................ 38
6

--[no]fields (f) (enabled) ......................................................................................................................................... 38


--[no]xaml (x) (disabled) ......................................................................................................................................... 38
--[no]virtual (enabled) ............................................................................................................................................ 38
--[no]overloaded (enabled) .................................................................................................................................... 39
--[no]flatns (n) (disabled) ........................................................................................................................................ 39
--[no]unicode [char set] (disabled) ......................................................................................................................... 39
--namelength <n> (1) .............................................................................................................................................. 39
Control Flow Obfuscation ............................................................................................................................................... 39
--[no]controlflow (enabled) .................................................................................................................................... 39
--iliterations <n> ......................................................................................................................................................... 40
--[no]invalidopcodes [mode] (disabled) ................................................................................................................. 40
Encryption and Protection.............................................................................................................................................. 40
--[no]msilencryption [regex] (disabled) .................................................................................................................. 40
--[no]stringencryption [name] (enabled)................................................................................................................ 40
--[no]valueencryption [name] (disabled)................................................................................................................ 40
--[no]ildasm (enabled) ............................................................................................................................................ 41
--[no]reflection (enabled) ....................................................................................................................................... 41
--[no]resourceencryption (disabled)....................................................................................................................... 41
--[no]proxy [type][;regex] (disabled) ...................................................................................................................... 41
Code Generation ............................................................................................................................................................ 41
--addreference <assembly> ....................................................................................................................................... 41
--[no]instrument [regex] (disabled) ....................................................................................................................... 41
--[no]emptymethods (enabled) .............................................................................................................................. 42
--[no]deadcode [regex] (disabled) .......................................................................................................................... 42
--[no]seal (disabled) ............................................................................................................................................ 42
--[no]cleanattrs (disabled) ...................................................................................................................................... 42
--[no]enumremoval (disabled)................................................................................................................................ 42
--[no]constremoval (disabled) ................................................................................................................................ 42
--[no]debug (disabled) ............................................................................................................................................ 42
Output Files .................................................................................................................................................................... 43
--output <file> ............................................................................................................................................................ 43
--pdb <file> ................................................................................................................................................................. 43
--logfile <file> ............................................................................................................................................................. 43
--mapout [file] ............................................................................................................................................................ 43
--makeproject [file] .................................................................................................................................................... 43
Input Files ....................................................................................................................................................................... 43
7

--keyfile <file>............................................................................................................................................................. 43
--keyname <container> .............................................................................................................................................. 43
--keypwd <password> ................................................................................................................................................ 43
--rules <file> ............................................................................................................................................................... 44
--mapin <file> ............................................................................................................................................................. 44
--project <file> ............................................................................................................................................................ 44
Configuration File ........................................................................................................................................................... 45
Processing Phases........................................................................................................................................................... 47
Obfuscation Agent .......................................................................................................................................................... 48
Rules File......................................................................................................................................................................... 50
Rules Element ............................................................................................................................................................ 50
Rule Element .............................................................................................................................................................. 50
Custom Attributes .......................................................................................................................................................... 54
System.Reflection.ObfuscateAssemblyAttribute ........................................................................................................... 54
System.Reflection.ObfuscationAttribute ....................................................................................................................... 54
Babel.Code.dll Assembly ................................................................................................................................................ 55
Merge and Embed Assemblies .....................................................................................................................................56
Assembly Merging .......................................................................................................................................................... 57
Merging Silverlight and WPF assemblies ........................................................................................................................ 58
Assembly Embedding ..................................................................................................................................................... 59
Symbols Renaming ......................................................................................................................................................61
Symbols Renaming ......................................................................................................................................................... 62
Unicode Character Set .................................................................................................................................................... 64
Overloaded Renaming .................................................................................................................................................... 64
XAML and BAML Obfuscation ........................................................................................................................................ 65
Silverlight XAML Obfuscation ......................................................................................................................................... 66
Obfuscating Windows Phone 7 Applications.................................................................................................................. 67
Control Flow Obfuscation ............................................................................................................................................69
Basic Control Flow Obfuscation...................................................................................................................................... 70
Enhanced Control Flow Obfuscation .............................................................................................................................. 71
Invalid Op-Codes ............................................................................................................................................................ 72
Encryption and Protection ...........................................................................................................................................74
MSIL Encryption.............................................................................................................................................................. 75
String Encryption ............................................................................................................................................................ 78
Inline Values and Array Encryption ................................................................................................................................ 80
Resource Encryption....................................................................................................................................................... 81
8

Dynamic Proxy Calls........................................................................................................................................................ 82


Code Generation .........................................................................................................................................................83
Automatic Class Sealing .................................................................................................................................................. 84
Removing of Unwanted Attributes................................................................................................................................. 84
System.Enum Types Removal ......................................................................................................................................... 85
Code Instrumentation .................................................................................................................................................86
Activating Instrumentation .......................................................................................................................................... 87
Simple Tracing Walkthrough .......................................................................................................................................... 88
Creating SimpleTrace Project ..................................................................................................................................... 88
Adding stub methods and building the project ......................................................................................................... 90
Creating an Obfuscation Test Project ........................................................................................................................ 90
Instrumenting the TestClient Application .................................................................................................................. 91
Visual Studio Integration .............................................................................................................................................93
Project File ...................................................................................................................................................................... 94
How to Add an XML Rule File in Visual Studio Project ................................................................................................... 94
Visual Studio Project File Samples .................................................................................................................................. 95
Enable Babel obfuscation on Release build only........................................................................................................ 95
Obfuscate Silverlight XAP package ............................................................................................................................. 95
Obfuscating .NET Micro Framework applications ...................................................................................................... 95
Post Build Event .............................................................................................................................................................. 96
MSBuild Task ...............................................................................................................................................................97
The Babel Task ................................................................................................................................................................ 98
Babel MSBuild Project Files .......................................................................................................................................... 101
Task Attributes ............................................................................................................................................................. 103
Customizing Project File Intellisense in Visual Studio .................................................................................................. 106
Advanced Topics ........................................................................................................................................................ 107
Silverlight XAP Packages ............................................................................................................................................... 108
Cross Referenced Members Obfuscation ................................................................................................................ 108
XAP Package Compression ....................................................................................................................................... 108
XAP Skip List ............................................................................................................................................................. 109
Satellite Assemblies ...................................................................................................................................................... 109
Strong Name Assembly Signing Using PFX Key............................................................................................................. 109
Obfuscating x64 Assemblies ......................................................................................................................................... 109
Customize MSIL Encryption .......................................................................................................................................... 110
Obfuscate Multiple Assemblies .................................................................................................................................... 112
Troubleshooting a Broken Application ......................................................................................................................... 114
9

Obfuscation Tips ........................................................................................................................................................... 115


Appendix A ................................................................................................................................................................ 116
Warning Codes ............................................................................................................................................................. 116
Unicode Character Ranges ........................................................................................................................................... 118
Index ......................................................................................................................................................................... 119
10

Conventions Used in This Manual


Various typefaces in this manual identify terms and other special items.
These typefaces include the following:

Typeface Meaning
Italic Italic is used for new terms or phrases when they are initially defined and occasionally for
emphasis.
Monospace Monospace is used for screen messages, code listings, command
samples, and filenames.
Code listings are colorized similarly to Visual Studio. Blue monospace type is used for
XML elements and C# keywords. Brown monospace type is used for XML element
names and C# strings. Green monospace type is used for comments. Red monospace
type is used for XML attributes. Teal monospace type is used for C# type names.
11

Introduction
Thank you for choosing Babel Obfuscator for the .NET Framework. This manual will guide you through the
use of the numerous features of this obfuscator. Babel was made with the goal of being easy to use and at the
same time deliver powerful obfuscation features.

Obfuscation at Glance
Obfuscation is a transformation process in which the code is changed to make it unclear and difficult to
understand, so that reversing is more difficult. Software written in .NET languages like C# and Visual Basic
are usually easy to reverse engineer because they compile to MSIL (Microsoft Intermediate Language), a
CPU- independent instruction set that is embedded into .NET assemblies, along with other information
(Metadata). This enables decompilation back to the original source code.

There are plenty of tools available online that enable the decompilation of .NET binaries into high-level
languages. The most popular are .NET Reflector and IDA. And the Microsoft .NET Framework SDK provides
ILDASM, a tool to disassemble .NET binaries to MSIL, making reverse engineering extremely easy. Since
MSIL is CPU independent, .NET assemblies can run on any platform that implements the CLR (Common
Language Runtime)—a software infrastructure necessary to execute .NET binaries. The drawback is that
software companies and IT professionals cannot protect their intellectual property if their software can be
decompiled.

Benefits of Babel Obfuscator


Babel Obfuscator is a tool for the .NET Framework to transform assemblies in order to conceal the code and
make reverse engineering difficult. The completely managed solution of MSIL Encryption ensures that the
code of the method is no longer accessible using the disassemblers available on the market. MSIL encryption
can be configured to strip code from the assembly and serialize it to encrypted files that can be loaded at
runtime from safe stores or license files. This method permits the deployment of your software with a reduced
set of features in the primary binaries in which the functionality can be activated only by access to the safe
store.

Babel also performs user string encryption and control flow obfuscation, hiding all the information that can be
used by reversers to identify and break software protection routines.

Symbol overload renaming reduces the resulting metadata size, which also reduces the overall size of the
obfuscated assembly and improves executable load time.

The integration with MSBuild enables Babel to be used in automated build environments, and thus
significantly reduces the time required to deliver the final product to testing and deployment.

Important note: A lot of effort was invested to ensure that the transformations performed by Babel are safe,
and the resulting software functionalities are not affected. Since obfuscation processes involve complex MSIL
changes, occasionally the obfuscated assembly could be compromised. To avoid this possibility the
obfuscated software should be thoroughly tested before deploying to the end users.
12

Software Requirements
The following software is required:

 A version of Windows that supports the .NET Framework 4.0. This can be Windows XP SP2,
Windows Server 2003 SP1 (including the R2 edition), Windows Vista and Windows 7.
 .NET Framework 4.0.
 The Windows Software Development Kit (SDK), specifically the .NET tools it includes. This is a
free download from http://msdn.com.

In addition, the following software is recommended:

 Visual Studio 2008 or later; an alternative free Express edition can be downloaded from
http://msdn.com
13

What’s New

Babel 5.6.0.0 changes

• Added Support for .NET Framework 4.5RC, Windows 2012 Server RC, Windows 8 RC
• Added the capability to turn on/off compression and encryption for embedded assemblies
• Improved speed of Merge algorithm
• Improved speed of Dead Code Removal
• Improved speed of generation for call graph
• Graphic user interface improvements
• Bug fixes (see Release Notes Bug Fixes)

Release Notes

Assembly version 5.6.0.0, File version 5.6.0.0

Enhancements

 Added Support for .NET Framework 4.5RC, Windows 2012 Server RC, Windows 8 RC
 Added the capability to turn on/off compression and encryption for embedded assemblies
 Graphic user interface improvements

Changes

 Improved speed of Merge algorithm


 Improved speed of Dead Code Removal
 Improved speed of generation for call graph

Bug Fixes

 Fixed: PFX certificate password cannot be entered during obfuscation


 Fixed: Dead Code Removal exception: Index and count must refer to a location within the string
 Graphic user interface fixes

The release notes for past releases are available at the following address:

http://www.babelfor.net/babel/release-notes
14

Babel Features
Babel Obfuscator is a powerful tool with many features available in three different editions: Standard,
Professional and Enterprise, to accommodate an increasing number of features and price.
15

Product Features
The main features are listed below:

General Features

 Works with Microsoft .NET Framework 1.1, 2.0, 3.5, 4.0, 4.5RC, .NET Micro Framework 3.0, 4.x,
Silverlight 3.0 to 5.0, Compact Framework, Windows Phone 7.0, 7.5, Xbox 360 XNA Framework
2.0, 3.0, 4.0.
 Selective Obfuscation with XML Rule Files
 XML Mapping Files
 Declarative Obfuscation using Custom Attributes
 Graphic User Interface
 Visual Studio Post-Build Integration
 MSBuild Integration
 Command Line Interface
 Supports Multiprocessor Execution
 Disables tools like .NET Reflector, Reflexil plug-in, and ILDASM
 One year of free product updates

Obfuscation

 XAML and BAML Obfuscation


 Obfuscates Namespaces, Types, Methods, Events, Properties and Fields
 Unicode Normalization and Custom Character Set
 Includes Generic Types and Virtual Function Obfuscation
 Public Members Obfuscation

Code Protection

 Dynamic Proxy Calls to External and Internal Methods


 MSIL Control Flow Obfuscation
 String Encryption
 Inline Values and Arrays Encryption
 MSIL Encryption
 Embedded Resources Encryption

Code Instrumentation and Optimization

 Code Instrumentation
 Dead Code Removal
 Automatic Class Sealing
 Attributes Cleanup
 System.Enum Type Removal
 Constant Fields Removal

Deployment

 Assembly Merging
 Assembly Embedding
 Supports Silverlight XAP Packages
 Automatic Obfuscation of Satellite Assemblies
 Supports re-sign with PFX and Strong Name Signature
16

 Supports decoding of obfuscated stack


17

Feature Matrix
Babel is available in 3 editions: Standard, Professional and Enterprise. The following table shows the features
included in each edition.

Features Standard Professional Enterprise

.NET Framework Support


Microsoft .NET Framework from 1.1 to 4.5 Beta,
Silverlight from 3.0 to 5.0, Compact Framework,
.NET Micro Framework 3.0, 4.x, Windows Phone
7.5, Xbox 360 XNA Framework from 2.0 to 4.5RC.
64 Bit Support
Silverlight XAP Package
Obfuscation
Symbol Renaming
Generic Types and Methods
XML Rule Files
Unicode Normalization
Overload Renaming
Custom Character Set Obfuscation
Public Symbol Obfuscation
XAML and BAML Obfuscation
Code Protection
Control Flow Obfuscation
1
Invalid Op-Codes
1
Prevent ILDasm
1
String Encryption
Inline Values and Arrays Encryption
Protection Against Reflection
Dynamic Proxy Calls (Internal/External Methods)
1
Resource Encryption
1
MSIL Encryption
Code Instrumentation and Optimization
Dead Code Removal
Automatic Class Sealing and Attributes Cleanup
System.Enum Type Removal
Constant Fields Removal
Code Instrumentation

1
Refer to Technology Matrix to see .NET Framework compatibility.
18

Deployment
Strong Name Signature with SNK
XML Map Files Generation
Debug PDB File Generation
Supports Resign with PFX Files
Assembly Embedding
Satellite Assemblies
Assembly Merging (WPF and Silverlight included)
Tools Integration
Command Line Interface
Visual Studio Post Build Events
MSBuild Support
Parallel Phase Execution
Product Maintenance
One Year of Product Upgrades
19

Technology Matrix
This table shows the availability of Babel Obfuscator features in relation to different .NET Framework version
and technologies.

Compact Framework
.NET Framework 4.x

.NET Framework 1.1

Silverlight 3.0 to 5.0

Windows Phone 7.x

XNA 4.0 XBOX360


Edition PRO/ENT

.NET Framework

Framework
.NET Micro
2.0 3.x
Obfuscation
STD Symbol Renaming
STD Generic Types and Methods - -
STD XML Rule Files
PRO Unicode/Custom Characters
PRO Overload Renaming
ENT Public Symbol Obfuscation
ENT XAML and BAML Obfuscation - - - - -
Code Protection
STD Invalid Op-Codes - - - - -
STD Prevent ILDasm - - - - - -
PRO Control Flow Obfuscation
PRO String Encryption XOR/Hash
PRO Encrypt Inline Values and Arrays
PRO Anti-Reflection Protection -
PRO Dynamic Proxy Calls - - - - -
PRO Resource Encryption - - - - -
ENT MSIL Encryption - - - - - -
Code Optimization
PRO
Dead Code and Const Fields
Removal
PRO
Automatic Class Sealing, Attribute
Cleanup
ENT
Code Instrumentation,
System.Enum Type Removal
Deployment
STD Strong Name Signature -
STD XML Map Files Generation
PRO Resign with PFX Files - - - -
PRO Silverlight XAP Packages - - - - - -
PRO Assembly Embedding - - - - -
ENT Satellite Assemblies - - -
ENT Assembly Merging
20

Licensing
Babel Obfuscator can be downloaded and installed for free. The product without a license file works in demo
mode. In this mode, the obfuscated assemblies will stop to work after 15 days from their generation. Also all
advanced obfuscation features like enhanced string encryption and control flow obfuscation are not available
in the product demo. To unlock the time expiration and enjoy the advanced obfuscation features you have to
purchase a license.

There are three different licensing schemas to accommodate an increasing number of features and prices:

 Standard
 Professional
 Enterprise

Babel Obfuscator is licensed per developer. This means that a license must be purchased for each developer
that uses Babel Obfuscator. There are no other restrictions or royalty fees for applications obfuscated with
Babel Obfuscator. With each license you receive 12 months of free updates from the date of purchase – be it
a minor service update or a major new version. After the 12 month period and at your discretion, you can pay
about 45% of original price to "renew" the subscription and receive another 12 months of free updates. If you
choose not to renew, you can continue using the last version you obtained or are eligible to use. The 12
month time frame is merely for new versions/updates and has no relevance to rights of use.

Standard Licensing
The Standard Licensing, allows you to own basic obfuscation features:

 Automatic Handling of Silverlight XAP Packages


 Custom Unicode Character Set Obfuscation
 Advanced String Encryption
 XML Configuration Rules
 Debug PDB Symbol File Support
 Resign with Strong Name Keys (SNK files)
 Debug PDB File Support
 Control Flow Obfuscation
 Support for Visual Studio, MSBuild and Command Line
 Graphic User Interface

The support for MSBuild and Microsoft Visual Studio as well as selective obfuscation with XML rules files, is
included in all product licenses.

Professional Licensing
The Professional license includes most of the advanced protection features available with Babel:

 Overloaded Renaming
 Dynamic Proxy Calls
 Values and Arrays Encryption

It also provides most of the code optimizations and deployment facilities such as:

 Dead Code Removal


 Automatic Class Sealing
 Assembly Embedding
 Support Resign with Personal Information Exchange (PFX) files
21

With these features you will be able to effectively obfuscate your assemblies, simplify and reduce the size of
deployed assembly removing not used code and embedding your references.

Enterprise Licensing
The Enterprise license is one that enables all the advanced features of the product. You will have, over the
features of the Professional license, also the MSIL code encryption and the possibility to obfuscate the
members used in the XAML and BAML code. Plus you will have the encryption of embedded resources and
more optimizations and deployment features including assembly merging and System.Enum type removal.
With assembly merging you will be able to merge all the dependencies into the main assembly, improving the
obfuscation of the deployed application.

Here are the features available only with the Enterprise edition:

Obfuscation

 XAML and BAML members obfuscation

Protection

 MSIL encryption
 Embedded resource encryption

Optimization and Code Instrumentation

 System.Enum type removal


 Constant fields removal
 Code Instrumentation

Deployment

 Assembly merging (WPF and Silverlight included)


 Automatic handling of satellite assemblies

Standard, Professional and Enterprise Additional Benefits


With all the editions you are entitled to have one year of free product updates. Minor and Major release
included. After one year you can renew your subscription for product updates and continue to receive new
product releases.
22

Licensing FAQ
Is your license on a per-developer basis?
Yes. Each developer must obtain a license. With this license, the developer can install on a primary machine
and a portable/laptop.

Do I have to pay you royalties?


No. babelfor.NET does not charge any royalties for redistribution of components obfuscated with Babel
Obfuscator.

Can I install the product on the build server?


Yes. You can install the product in your build server and use your license. In any way you need to have
enough licenses to cover all the developers accessing the build services.

Can I install the product on 2 machines (I'm running a desktop in the office, have a laptop at home)?
Yes.

Can I continue to use Babel Obfuscator if the subscription expires and I choose not to renew?
Yes. You can continue to use Babel Obfuscator which you have licensed and paid for...as long as you require.
When a subscription expires, it simply means that you will no longer be issued any product updates or new
product releases.
An expired subscription can be renewed. If you do not renew your subscription on the 13th month after
purchase, your renewal cost will increase on a monthly basis. Feel free to contact our client services for more
information on renewals and product costs once your subscription expires.

License File
After purchasing Babel Obfuscator you will receive a license file. This file needs to be copied into the Babel
installation root folder; usually “C:\Program Files\Babel” and it enable the features that are associated with the
edition purchased. The license file itself is an XML file digitally signed and encloses information about the
product, customer details and other encrypted data specific to the license purchased.

You can access your license information by typing into a DOS shell:

babel --license

If a valid license is not found the following message will be displayed:

Error: A valid babel license could not be found. Please contact http://www.babelfor.net
for assistance.

Note that any modification to the XML license file will invalidate the license itself. Also if you own a trial or beta
license that has an expiration date, do not run Babel after setting back the computer system time or your
license will be automatically invalidated.

Standard, Professional and Enterprise licenses do not have an expiration date. Every license comes with one
year of free product upgrades. At the end of this period you have the option to renew the product maintenance
subscription and stay up to date with all the new releases for another year. Otherwise you will stay with the
version released when the product maintenance subscription has expired.
23

Babel Obfuscator Version History


Babel Obfuscator was available for free until release 2.0.0.1.
In the release version 3.0.0.0, has been introduced some major improvements and the product was made
available under a commercial license.

The main differences between the commercial and the free version are listed below:

Latest Babel Obfuscator Commercial Version


 Support for .NET Framework 4.0, Silverlight 3.0  Attributes Removal
to 5.0, Windows Phone 7.x, Xbox 360 XNA  System.Enum Types Removal
Framework and .NET Micro Framework 3.0, 4.x  Constant Fields Removal
 Graphic user interface  Multiprocessor Execution
 Compatible with FIPS standards  Performance Improvements
 Full symbols renaming  Major Fixes on Symbol
 Silverlight XAP Package Support Renaming and Metadata
 XAML Parsing for Silverlight Applications Verification
 Assembly Merging  Log File Output
 Assembly Embedding  PDB File generation
 Embedded Resources Encryption  Custom Unicode Obfuscation
 MSIL Encryption Character Set
 Anti-Reflection Protection  Automatic Obfuscation of
 XAML and BAML Obfuscation Satellite Assemblies
 Dynamic Proxy Calls to External and Internal  Public Symbol Obfuscation
Methods  Revisited Control Flow
 Code Instrumentation Obfuscation
 Enhanced Control Flow Obfuscation  Improved Overload Renaming
 Enhanced String Encryption  Extended XML Rules Files
 Inline Value and Array Encryption  SNK and PFX File Support
 Automatic Class Sealing  Extended Command Line Help
 More than 20 new Command
Line Options

The Free Babel Obfuscator Version 2.0.0.1


 Support NET Framework 1.1, 2.0, 3.5
 Obfuscate Namespace, Type (also generic types), Method, Events, Properties and Fields
 Unicode Normalization
 Support Generic Types and Virtual Function Obfuscation
 Basic Control Flow Obfuscation
 Basic String Encryption (XOR algorithm only)
 Dead Code Removal
 Selective Obfuscation with XML Rule Files
 Declarative Obfuscation using Custom Attributes
 MSBuild Integration
 SNK Strong Name Signature
24

Overview
The following sections will guide you through the software setup and basic understanding of command-line
usage. The section Processing Phases will be a review of the obfuscation process performed by Babel. If you
want to start using Babel right away, you can begin by reading from the Rules File section, just to get a basic
understanding of how to configure the obfuscation process. Babel comes with extended command-line help
syntax so that you can access the detailed help of each command line option by typing babel –help (option
name). The code transformations performed by Babel are grouped into phases. This manual will show you in
detail what each phase does and how it can be configured using XML rules files. Following are the Visual
Studio Integration and MSBuild Task sections. Those sections explain how to use Babel within Visual Studio
and how to integrate the Babel Obfuscator into automated build processes. In the Advanced Topics section
you will find some useful tips on improving your obfuscation and getting the most out of Babel. I have also
included a quick reference explaining the warning messages that Babel can output (Appendix A).

If you have any comments or suggestions about the software, the website, or this help guide, please contact
our support at support@babelfor.net
25

Starting Using Babel


Obfuscator
This section will describe how to setup Babel Obfuscator and the basic usage of the user interface. The Babel
Obfuscator User Interface allows the user to obfuscate an application in few steps making easy to generate
obfuscation project files that are compatible with MSBuild.
Then you will find a detailed description of the command line interface and the XML Rules Files that are
available to configure the obfuscation process.
26

Setup
Babel Setup is available for 32 bit and 64 bit Windows platform as an MSI installer package. The deployment
package is named babel_x86_5.6.0.0.msi for 32 bit and babel_x64_5.6.0.0.msi for 64 bit operating systems.
They both provide the same compiled executable targeting all platforms. The only difference is in the location
of the installed files.

The 32 bit setup will install the Babel folder under the Program Files folder, whereas the 64 bit version will
install the Babel folder under the Program Files 64 folder. If you run the setup package suited for 32 bit
version on 64 bit operating systems the Babel folder will be copied under the Program Files (x86) directory.

! NOTE
If you have a previously installed version of Babel Obfuscator, uninstall it from Control Panel before
installing the new version.

To install Babel, launch the Setup MSI installer. This package will guide you through the install process. On
Vista and Windows 7 operating systems you should confirm the Allow button in the User Access Control
dialog during installation.

Once installed, if you want to launch Babel from the DOS command shell, add the babel.exe executable file
path to the environment user variable PATH. Open

• Start > Control Panel > System > Advanced system settings > Environment Variables.

In the User variables list box double click the PATH variable. Or if that does not exist, press the New button
and edit in the New User Variable Dialog the following fields:

Variable name: PATH


Variable value: C:\Program Files\Babel

Variable value field should point to the installation path.


Now you are ready to open a command shell and start babel.exe.
27

Babel Obfuscator User Interface


To start Babel Obfuscator user interface browse:

• Start > All Programs > Babel > Babel

The user interface will be started with the Input navigation link selected.

1) Primary Source Drop Down


2) Primary Source Assembly Input Grid
3) Group Navigation Panel
4) Obfuscation Group
5) Tools Group
28

Creating a New Solution File

• In the Input group browse for the assembly you would like to obfuscate
• Select File > Save As to save the solution file with .babel extension

The Babel solution file is an MSBuild XML file that groups a set of Babel obfuscation projects. Each project
holds the Babel MSBuild task configuration to obfuscate an assembly inside the solution. This allows the user
to launch the obfuscation from the command line using the MSBuild tool.

Load the Primary Source Assembly


To add a primary source assembly into your solution:

• Click the […] button that is shown on the right of the File record inside the Input grid.
• Browse for a Primary Source Assembly: a .NET Framework EXE or DLL file or a XAP Package.

You can also drag & drop one or more primary source assemblies from Windows Explorer directly into the
Input grid.

Each Primary Source Assembly added, will be shown in a separate row of the input grid. By clicking on the
expand button near the input File column, the additional file grids will be shown. There are three tabs: Inputs,
Rules and Map, and each one group different additional files.
29

The input section is where you can choose the assemblies that you want to merge or embed into the primary
assembly. The Rules section is where you can add your XML rules files that Babel will process when
obfuscating the related primary assembly. Finally the Maps section is where to add XML input mapping files.

You can always use drag & drop from Windows Explorer to add your files to each of the available sections.

! NOTE
In case you have many primary assemblies in your input grid and you want to add an XML rule file to more
than one primary assembly, just expand one of the primary assembly row where you want to add the XML
rule file, select the Rules tab, then select in the Input grid all the other primary assembly rows where you want
the XML rules to be applied. From the expanded Rules tab press the browse button and choose the XML rule
file. The file will be added to all the selected primary assemblies. The same applies for the Inputs and Maps
grids.

You can use the bottom grid navigator bar to remove the primary source assemblies or others files from the
details panels.

The input assembly grid allows you to change the order in which the assemblies are obfuscated by simply
drag & drop each primary source assembly into the desired row. The primary source assemblies are
processed starting from the first row.
30

Changing Obfuscation Settings


Once you have set up all your inputs assemblies, you can proceed to the Settings link to configure the
obfuscation options:

• Click the Settings link on the Group Navigation Panel to change the obfuscation settings.
• In the program toolbar ensure that the name of the primary assembly you want to change obfuscation
settings is selected.

You can also press the Propagate changes button on the toolbar next to the Primary Assembly drop
down. When the Propagate changes button is pressed, all the changes made to the selected Primary
Source will propagates to all the Primary sources loaded.

• On the left panel drag the Obfuscation Level slider up to increase the obfuscation amount that will be
performed on the selected Primary source. You can fine tune settings by changing the options
available on each section.

Code Generation Options


You can select the Optimization link on the Navigation panel to setup code generation and optimization
options.

• Select Remove Dead Code if you want to remove all the code that is not reachable from any entry
point in the obfuscated target. Additional entry points can be specified by using regular expressions to
describe the method signature where Babel should start the search.
• You can optimize further, by sealing classes or removing System.Enum types and constant fields
whenever it is possible. Babel can also remove all the custom attributes that are specified in the grid
Attributes.
31

Setting the Output and Building the Project


The Output link in the Navigation panel lets you to set up the output file or folder and some additional
configuration like the strong name signature.

If you want to configure an output folder for all the obfuscated assemblies that are loaded into your
obfuscation project, you can activate the Propagate changes button in the toolbar and then choose from the
drop down button the Output Folder option. Then browse for the output folder where you want to save all the
obfuscated assemblies. You can check that the output folder is set for all the primary sources by changing to
another primary source from the drop down in the toolbar.

On the application toolbar click the Start button to start the obfuscation.
32

1) Primary Source Assembly obfuscation progress


2) Overall Obfuscation progress

The Console navigation link will let you examine the Babel Obfuscator output while the obfuscation is running.
You can select the Primary Source from the drop down toolbar to see the relative obfuscation output.

Examine the Obfuscated Assemblies


To browse for the Obfuscation output folder, click the up arrow button located next to the Output File /
Output Folder text box. Then you can drag the output assembly into .NET Reflector to examine the
obfuscated code or simply run the application.
33

Deobfuscating Stack Trace


When an obfuscated assembly crashes, it is difficult to get useful information from the exception stack trace
because most of the time it contains the obfuscated methods names. Babel can make obfuscated stack trace
readable using the XML mapping files produced during the obfuscation process. To de-obfuscate the stack
trace you can select the Stack Decoder link available in the Tools navigation group.

• Select Tools in the navigation group then click the Stack Decoder link.
• In the XML Map File grid browse for one or more XML map files that were generated during the
obfuscation of your application.
• Paste the obfuscated stack trace into the Obfuscated Stack Trace text box.
• Click the Deobfuscate Stack Trace button

The translated stack trace will be shown in the Deobfuscated Stack Trace text box.
34

Launching Babel from Command Line


You can start Babel from the command line. Browse for the Babel Command Prompt available at:

• Start > All Programs > Babel > Babel Command Prompt

You can launch babel.exe using the following syntax:

babel.exe <primary assembly source> [<other assemblies>...] [options]

The <primary assembly> is the target assembly that we want to obfuscate and it is mandatory.

! ! NOTE
In the Babel command line syntax every mandatory parameter is surrounded by angle brackets <…>,
whereas every optional parameter is surrounded by square brackets […].

The [<other assemblies>…] is an optional list of assemblies that will be merged with the primary assembly.
The [options] are a list of command line switches that control the behavior of Babel. There are many options
and they are grouped into several sections:

Miscellaneous
This section contains all general options that are used to configure the console output and other aspects of
the obfuscation process.

--help [option] (?)


Typing Help without any parameters shows the main help menu with all the options available and a short
description. When [option] name is specified, Babel will show extended help with the detailed command
description.

C:\> babel --help stringencryption


stringencryption (nostringencryption, no-stringencryption)
usage: --[no]stringencryption [name]
Enable ([no]disable) string encryption (default: enabled)

When enabled, all the user strings into the target assembly will be encrypted.
The optional parameter name sets the encryption type.

hash - Compressed hash table. The strings are arranged into compressed encrypted
hash table data. This algorithm ensures tamper protection.
xor - Inline xor strings.

The hash algorithm is used when a valid license is present; otherwise the xor
algorithm is used.
35

The short form for this option is invoked by the character “?”.

! NOTE
Babel has numerous command line options, but there are two distinct kinds of options: short options
and long options. Short options are a single hyphen followed by a single letter. Long options consist of
two hyphens followed by a number of letters (e.g., -t and --types, respectively). Every option has a long
format and sometimes an alias as well. But only certain options have an additional short format (these
are typically options that are frequently used). To maintain clarity, we usually use the long form in the
examples, but when describing options (if there's a short form) we'll provide the long form to improve
clarity and the short form to make it easier to remember. You should use whichever one you're more
comfortable with.
An option may have an alias. Aliases provide shortcuts for long options. For example --keyfile option
has the alias --kf. When Babel parses long option names, it uses auto abbreviation to resolve the
option.
So --statistics can be shortened to --stat. Some options can be negated. These options are like
switches that can be turned on or off according to the no or no- option prefix. For example the --types
enables type name obfuscation whereas --notypes, --no-types or -not disable it.

--[no]logo (enabled)
This option shows the Babel copyright message. If the optional prefix [no] is specified the copyright message
will not be shown.

--license
Displays available license information. If a valid license is not found, an error message will be displayed.

--verbose <n> (v)


Sets the console output verbosity level when <n> is 0 or higher. If 0 is specified, no messages are displayed
during obfuscation; only warning messages and the Babel logo are displayed.

--noconfig (@) (disabled)


Do not load default configuration command line values. When specified, all the default values stored in
babel.exe.config file are ignored.

Examples:

babel myapp.exe --noconfig --agent -tpm

babel myapp.exe @ --agent -tpm

Will obfuscates myapp.exe types, properties and methods with the agent analysis enabled.

--nowarn <warn list>


Suppress the notification of one or more warning messages. The <warn list> parameter represents a list of
warning ID separated by a comma character. Babel will silently ignore warning numbers passed to the nowarn
option. All available warning IDs are listed in Appendix A.
36

--[no]warnaserror [warn list]


Specifies a list of warnings that should be treat as errors. The [warn list] is an optional comma-delimited list of
the warning ID to which the warnaserror option applies. By default warnings do not prevent Babel from
producing an output file. All available warning IDs are listed in Appendix A.

--[no]statistics (enabled)
When enabled, outputs phase processing statistics just before exiting the program.

--[no]agent (a) (enabled)


This option enables or disables Agent Phase. When enabled, the Agent performs static code analysis to find
symbols that should not be obfuscated.

--[no]satellite [assembly]
Treat [assembly] file as a satellite assembly of the target assembly. Babel will add to the list of satellite
assemblies automatically discovered all the assemblies specified with this switch at the command line.

--addsearch <path>
Adds the specified directory <path>, to the list of folders where Babel searches for referenced assemblies.

--take <regex>
Process the XAP package assembly names that match a given regular expression. If not specified, Babel will
obfuscate all assemblies that are deployed by the XAP package. These assemblies are found under the
Deployment.Parts element in the AppManifest.xaml file:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
EntryPointAssembly="OrbSl3" EntryPointType="OrbSl3.App"
RuntimeVersion="3.0.40624.0">
<Deployment.Parts>
<AssemblyPart x:Name="Silverlight3App" Source="Silverlight3App.dll" />
</Deployment.Parts>
</Deployment>

This option may be specified multiple times.

Examples:

babel package.xap --take ".*gui\.dll" --take ".*engine\.dll"

Will obfuscates all the DLLs file names that ends with “gui” or “engine” words. The match is done using case
insensitive search.

--skip <regex>
Do not process the XAP package assembly names that match a given regular expression.
If not specified, Babel will obfuscate all assemblies that are deployed by the XAP package. These assemblies
are found under the Deployment.Parts element in the AppManifest.xaml (see also --take command).

--compress <n> (6)


Set XAP package compression level (default: 6).
37

XAP compression level must be between 0 and 9. If 0 is specified, the XAP package will not be compressed
at all. A value of 1 maximizes speed while 9 maximize compression. The default value is 6. High compression
level may reduce XAP package size, increasing the computational time required during decompression.

--quickrule <rule>
Enter a quick rule definition. A quick rule can be used instead of an XML rule when the user wants to
configure the obfuscation process without having to make an XML rule file.

Quick rule syntax:

feature[=exclude];[regex];[access];[target]

Where:

 feature is the name of the feature the rule wants to target


 [=exclude] has to be specified whether we wants disable the feature (On or Off are also accepted
values)
 [regex] is an optional regular expression used to filter all symbols processed. By default the
obfuscator will take all symbols.
 [access] set the visibility of the symbols that should be processed and can be one of the following
values: Public, Protected, Internal, Private, All (default All)
 [target]specifies the symbol kind. Admitted values are: Classes, Delegates, Structures, Interfaces,
Enums, Events, Methods, Properties, Fields, StaticFields, Resource, All (default All)

The quickrule switch can be entered multiple times. Quick rules will be processed in the order they are
encountered on the command line and before the processing of any XML rule.

Examples:

1. Rename all public symbols

babel myapp.exe –quickrule renaming;.*;Public

2. Disables string encryption into MyNamespace namespace

babel myapp.exe –quickrule "string encryption=exclude;MyNamespace.*;All;Methods"

3. Encrypt all methods defined into Licensing class:

babel myapp.exe –quickrule "msil encryption=on;MyApp.Licensing.*"

Merge and Embed Assemblies


Assembly merging combines a list of assemblies into the primary assembly. This functionality is similar to that
provided by ILMerge, a tool freely available at Microsoft .NET Framework Developer Center. Babel has its
own merging algorithm that has been proven to be more efficient and less error-prone than the one provided
by ILMerge. Babel merges and obfuscates all the assemblies that are listed after the primary assembly in the
command line.

--[no]internalize (disabled)
If enabled, all the externally visible types in the merge assembly list have their visibility restricted so that only
the target assembly may use them.
38

--[no]copyattrs (enabled)
When this option is enabled, all the assembly level attributes of each input assembly are copied into the target
assembly. Duplicate attributes are discarded.

--embed <assembly>
Babel can embed multiple dependency assemblies into the target assembly. The embedded assemblies are
compressed and encrypted. Embedding can simplify the deployment and reduce the size of the software. It
can be used instead of merge when there is no need to fully obfuscate the dependency assembly.

This option can be specified multiple times.

babel.exe myapp.exe --embed Library1.dll --embed Library2.dll

Renaming
This command line section describes the commands that can be used to configure symbol renaming.

--[no]types (t) (enabled)


If disabled, types are not renamed.

--[no]events (e) (enabled)


If disabled, events are not renamed.

--[no]methods (m) (enabled)


If disabled, methods are not renamed.

--[no]properties (p) (enabled)


If disabled, properties are not renamed.

--[no]fields (f) (enabled)


If disabled, fields are not renamed.

--[no]xaml (x) (disabled)


If enabled, symbols used in XAML and BAML resources are renamed. This option is able to accept optional
key value pair specified as <key>=<value> that configures the renaming process. The configuration options
accepted are:

 manual = {On/Off} Whether to use manual symbol renaming


 keys = {On/Off} Whether to enable renaming of dictionary keys
 strip = {On/Off} Whether to strip line information or white spaces

--[no]virtual (enabled)
If disabled, virtual members such as methods, properties and events, are not renamed.
39

--[no]overloaded (enabled)
If enabled, Babel uses the same name for two or more methods of the same type during obfuscation.

--[no]flatns (n) (disabled)


If enabled, all the types are moved into the global namespace. This flattens the namespace hierarchy and no
namespace information is embedded into the obfuscated assembly.

--[no]unicode [char set] (disabled)


If enabled, the names are replaced with unreadable Unicode strings. With Unicode normalization disabled all
the obfuscated names are made by strings of lowercase characters taken from the Latin alphabet. Optionally
the user can specify the character set used to generate obfuscated names (see Unicode Character Set).

--namelength <n> (1)


Set the minimum name length of renamed symbols. Optionally key value pairs can be entered to set the
minimum length of types, methods, properties, fields and events separately.

 types=<n>
 mehods=<n>
 properties=<n>
 fields=<n>
 events=<n>

Example:

babel.exe myapp.exe --namelength types=12 --namelength methods=3

Control Flow Obfuscation


The MSIL Control Flow Obfuscation phase is processed when either controlflow or invalidopcodes are present
in the command line. This phase produces a transformation of the method MSIL changing the code execution
path so that results are difficult to understand.

--[no]controlflow (enabled)
If enabled, methods’ control flow is altered. Key-value pair <key>=<value> can optionally be entered to
configure code scrambling. The configuration options accepted are:

Produces verifiable MSIL code

 goto ={On/Off} Whether to insert irrelevant branches


 switch = {On/Off} Whether to enable switch scrambling
 case = {On/Off} Whether to hide case constants
 if = {On/Off} Whether to enable if scrambling
 call ={On/Off} Whether to enable random calls
 values={On/Off} Whether to use value encryption
 token ={On/Off} Whether to enable emission of method tokens

Produces not verifiable MSIL code

 underflow={On/Off} Whether to generate stack underflow


40

--iliterations <n>
Set the number of iterations used in the control flow obfuscation algorithm. Setting the number of iterations to
0 will disable control flow obfuscation. Increase the value <n> to increase the number of branch instructions
inserted into each method.

--[no]invalidopcodes [mode] (disabled)


Use this option to emit invalid MSIL op-codes at the beginning of every method. This will stop reflection tools
like .NET Reflector to display IL method disassembly. Warning: This will make your assembly not verifiable.
Normally, code that is not verifiable cannot run on x64 Operating Systems. This option should be switched off
if the obfuscated assembly targets x64 platforms.

The optional parameter [mode] enables different IL emission configuration. Accepted values are:

 enhanced: Insert additional invalid op-codes.


This mode is not compatible with .NET Framework 1.x.

Encryption and Protection


MSIL encryption option enables the encryption of the method IL code. By default this option by itself does
nothing if the encrypted methods are not explicitly assigned to be encrypted by means of rules or with suitable
custom attributes. This explicit method designation is required because the resulting encrypted method call is
much slower than the original one and the user should be aware of all the methods that will be encrypted in
the target assembly.

--[no]msilencryption [regex] (disabled)


If enabled, MSIL Encryption Phase is performed and all the methods that were designated for encryption will
be processed. The methods that will be encrypted are those matching the optional regular expression or rules
defined into XML files. This option can be specified multiple times.

--[no]stringencryption [name] (enabled)


This option, when enabled, tells Babel to encrypt all the user strings into the target assembly. If the optional
parameter name is provided, the encryption will be performed according the algorithm specified.

The known algorithm names are:

 hash – compressed hash table:


The strings are arranged into an hash table data that is compressed and encrypted. This
algorithm ensures also tamper protection.
 xor – inline XOR encoded strings

The default algorithm is hash when a valid license is present, otherwise is the xor algorithm.

--[no]valueencryption [name] (disabled)


This option enables the encryption of inline constant values and arrays. Key-value pair <key>=<value> can
optionally be entered to enable or disable the encryption of some defined types.

The configuration options accepted are:

 int32 ={On/Off} Whether to encrypt Int32 values


 int64 = {On/Off} Whether to encrypt Int64 values
 single = {On/Off} Whether to encrypt Single values
41

 double = {On/Off} Whether to encrypt Double values


 array ={On/Off} Whether to encrypt Arrays

--[no]ildasm (enabled)
When enabled, Babel applies the System.Runtime.CompilerServices.SuppressIldasmAttribute attribute to the
assembly to prevent the Microsoft MSIL Disassembler: ILDASM (Ildasm.exe) from disassembling the
obfuscated target.

--[no]reflection (enabled)
Enables or disables emission of invalid metadata to stop reflection based tools.

--[no]resourceencryption (disabled)
Enables or disables resource encryption. When enabled, all the embedded resources are compressed and
encrypted.

--[no]proxy [type][;regex] (disabled)


Enables or disables the generation of proxy calls to external/internal methods. The optional parameter [type]
can have one of the following values:

 external – hide calls to external assembly methods


 internal – hide calls to internally defined assembly methods
 all – hide both internal and external method calls

Optionally the user can enter a regular expression, after the character “;”, to match the method signature
where Babel should make a proxy:

babel.exe myapp.exe --proxy external --proxy ;System.Array::.* --proxy ;::GetEnumerator

Babel will generate a proxy for all external methods of the System.Array type and all the GetEnumerator calls.

Code Generation
With code instrumentation babel can hook all the methods of the obfuscated target and intercept all methods
entry and exit point or catch any exception occurred.

--addreference <assembly>
Add existing assembly file to the list of references.

--[no]instrument [regex] (disabled)


When this option is enabled, all methods declared into the target and merged assemblies are instrumented.
An optional regular expression can be specified to target the fully qualified members that should be
instrumented.

Fully qualified members have the following syntax:

[NamespaceName].[TypeName]::[MethodName]

Example:
42

babel.exe myapp.exe –-instrument mynamespace\.mytype::.*

This option can be entered multiple times.

--[no]emptymethods (enabled)
Enables or disables the instrumentation of empty methods.

--[no]deadcode [regex] (disabled)


Enable or disables the Dead Code Removal phase. When enabled, removes all methods, properties and
events that are unused. An optional entry point can be specified through [regex] to define where to start the
search.

--[no]seal (disabled)
When enabled seal all non-public classes that are not used as base class in an inheritance hierarchy.

--[no]cleanattrs (disabled)
Enable or disables the removal of unwanted attributes.

--[no]enumremoval (disabled)
Enable or disables the removal System.Enum types whenever possible. The System.Enum fields are replaced
with their constant values.

--[no]constremoval (disabled)
Enable or disables the removal of constant fields whenever possible. The fields are replaced with their
constant values.

--[no]debug (disabled)
When enabled, Babel will emit the debugging information and generates a PDB debug symbol file in the same
directory of the obfuscated target. Use the –pdb command line switch to change the debug symbol file name
and path.
43

Output Files
This section provides Babel the option to set output filenames.

--output <file>
Set the output file path for the obfuscated target. If this option is not provided, the obfuscated target will be
saved into the BabelOut subdirectory of the original assembly folder.

--pdb <file>
Set the output PDB debug symbol file name and path. This option can be used to change the default debug
file symbol name when the --debug option is enabled.

--logfile <file>
Send the Babel output messages to a log file.

--mapout [file]
Set the output file name for the XML obfuscation map. If the optional parameter [file] is not provided, Babel will
name the XML map file as the original assembly name, adding the extension “.map.xml”.

--makeproject [file]
Build an MSBuild project file from the entered command line. If the optional parameter [file] is not provided,
Babel will save the project file into the BabelOut subdirectory.

Input Files
The Input Files section contains options that are used to pass additional inputs to Babel.

--keyfile <file>
Set the strong name file used to re-sign the obfuscated assembly and localized resource DLLs.

The supported file formats are: Strong Name Key (.snk) and Personal Information Exchange (.pfx).
When a .pfx file is used, Babel will ask the user to enter the password during obfuscation in case it was not
specified in the command line option (--keypwd <password>).

--keyname <container>
Use this option to re-sign the application if the key pair is stored in a key container. The mandatory
<container> parameter represents the key container name used to re-sign the obfuscated assembly and
localized resources DLLs.

--keypwd <password>
Specifies the password requested by a Personal Information Exchange (.pfx) file to re-sign the obfuscated
assembly. When the password is not specified from the command line, Babel will require the user to enter the
proper password during the obfuscation process.
44

--rules <file>
Set the input XML rule files used by Babel to configure the obfuscation process. This option can be specified
multiple times. The rules files will be processed according to the order in which they are entered into the
command line.

babel.exe myapp.exe --rules ruleset1.xml --rules ruleset2.xml

--mapin <file>
Set the input XML obfuscation map file that will be used to obfuscate the names of referenced symbols. This
option can be specified multiple times.

--project <file>
Start the obfuscation using the project file specified.
45

Configuration File
Each option that can be passed to the command line has a default value that is stored in the babel.exe.config
application configuration file. When the user does not explicitly specify an option at the command line, Babel
will use the default value for that option. Default values are loaded from the babel.exe.config file. The
application configuration file is a standard .NET XML configuration file. It contains elements which are
name/value pairs for configuration information. The following table shows all possible configuration elements:

Name Default Type


Value
AssemblySearchDirectories empty System.Collection.Specialized.StringCollection
AutomaticClassSealing True System.Boolean
BabelProjectAddNewLineOnAttributes False System.Boolean
CleanupUnwantedAttributes True System.Boolean
ConsoleForeColorDebug DarkGray System.ConsoleColor
ConsoleForeColorError Red System.ConsoleColor
ConsoleForeColorInfo White System.ConsoleColor
ConsoleForeColorWarning Yellow System.ConsoleColor
ConsoleHighlight True System.Boolean
ConstFieldsRemoval False System.Boolean
ControlFlowAddBranches True System.Boolean
ControlFlowAddMethodToken False System.Boolean
ControlFlowAddSwitchStatement False System.Boolean
ControlFlowChangeIfStatement False System.Boolean
ControlFlowComplexifyDecryptStringCalls False System.Boolean
ControlFlowEncryptSwitchValue False System.Boolean
ControlFlowHideCaseConstants False System.Boolean
ControlFlowIterationCount 3 System.Int32
ControlFlowObfuscation True System.Boolean
ControlFlowRandomCall False System.Boolean
ControlFlowStackUnderflow False System.Boolean
CopyAttributes True System.Boolean
DeadCodeElimination False System.Boolean
DeadCodeRemovalWhipeoutObjectVirtuals False System.Boolean
DisableWarnings empty System.Collection.Specialized.StringCollection
DynamicProxy none System.String
DynamicProxyCallFilters empty System.Collection.Specialized.StringCollection
EmitInvalidOpcodes False System.Boolean
EmitInvalidOpcodesMode empty System.String
EnumTypeRemoval False System.Boolean
FlattenNamespaces True System.Boolean
GenerateDebug False System.Boolean
Instrument False System.Boolean
InstrumentEmptyMethods True System.Boolean
Internalize False System.Boolean
MapFileNameEncoding Base64 System.String (Base64/None)
MinimumEventNameLength 0 System.Int32
MinimumFieldNameLength 0 System.Int32
MinimumMethodNameLength 0 System.Int32
MinimumNameLength 0 System.Int32
MinimumPropertyNameLength 0 System.Int32
MinimumTypeNameLength 0 System.Int32
MsilEncryption False System.Boolean
ObfuscateEvents True System.Boolean
ObfuscateFields True System.Boolean
ObfuscateMethods True System.Boolean
ObfuscateProperties True System.Boolean
ObfuscateTypes True System.Boolean
46

Name Default Type


Value
ObfuscateVirtualFunctions True System.Boolean
ObfuscateXaml False System.Boolean
ObfuscationAgent True System.Boolean
OverloadedRenaming True System.Boolean
ParallelExecution True System.Boolean
ProcessReferencedSymbolNames True System.Boolean
ResourceEncryption False System.Boolean
ResourceNameSearchFilters System.Collection.Specialized.StringCollection
SearchSatelliteAssemblies True System.Boolean
ShowLogo True System.Boolean
ShowStatistics True System.Boolean
StringEncryption True System.Boolean
StringEncryptionAlgorithm empty System.String
SuppressIldasm True System.Boolean
SuppressReflection False System.Boolean
UnicodeNormalization True System.Boolean
UnwantedAttributes <list> System.Collection.Specialized.StringCollection
ValueEncryption False System.Boolean
ValueEncryptionInt32 True System.Boolean
ValueEncryptionInt64 True System.Boolean
ValueEncryptionSingle True System.Boolean
ValueEncryptionDouble True System.Boolean
ValueEncryptionArray True System.Boolean
VerboseLevel 1 System.Int32
WarningsAsError empty System.Collection.Specialized.StringCollection
XamlManualRenamePublic False System.Boolean
XamlObfuscateResourceKeys True System.Boolean
XamlStripLineInfo True System.Boolean
XapCompressionLevel 6 System.Int32
XapSkipList <list> System.Collection.Specialized.StringCollection

The default value for DisableWarnings, WarningsAsError and XapSkipList are empty
System.Collection.Specialized.StringCollection. To add elements to these configuration sections you should
add an ArrayOfString element. For instance to add elements to the DisableWarnings collection enter the
following XML in the configuration file:

<setting name="DisableWarnings" serializeAs="Xml">


<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>EM0008</string>
<string>EM0010</string>
</ArrayOfString>
</value>
</setting>

Where EM008 and EM0010 are warning IDs. The complete set of warning IDs is listed in Appendix A.
47

Processing Phases
The transformations that Babel performs during the obfuscation process are grouped into phases. We may
define a phase as a processing unit. Babel has a list of Phases that are processed during obfuscation. This
list is not absolute and may vary according to the options passed to the command line. To configure the
obfuscation process with rules it is necessary to understand how Babel organizes the phased layout. The
phases that Babel arranges in its obfuscation list are outlined below in the order they are processed,
according to the option passed to the command line.

Phase List Command Line Options Description


Merge Input Assemblies Phase List of assemblies to process Process XML rules files and
Merge input assemblies.
Post Reader Phase Analyze the target assembly
Build Call Graph Phase Build the method call graph.
Process Rule Phase --rules Process XML rule files
Agent Phase --agent Performs Agent tasks
Dead Code Removal --deadcode Remove unused members
Build Map Phase --mapout Build target map document
Code Instrument --instrument Enable code instrumentation.
Code Optimizations --seal Code optimizations
--cleanattrs
--enumremoval
--constremoval
Dynamic Proxy Calls --proxy Generate dynamic proxies
Renaming --types, --methods, Rename assembly symbols
--properties, --fields, --events
Encrypt MSIL Phase --msilencryption Encrypt MSIL
Encrypt Values Phase --valueencryption Encrypt values and arrays
Encrypt String Phase --stringencryption Encrypt all strings
Control Flow Obfuscation Phase --controlflow --invalidopcodes Scramble MSIL code
Embed Assemblies Phase --embed Embed assemblies
Encrypt Resources Phase --resourceencryption Encrypt embedded resources
Emit Phase Save and sign the resulting
assembly
Table 1 Obfuscation Phases

Some phases are necessary to the build process (such as Post Reader Phase and Emit Phase) and they will
always be present. Other phases are added only when they are needed, like Merge Input Assemblies and
Process Rules. For instance, the Process Rules phase is added when the user specifies a rule file in the
command line. The following diagram shows the flow of the Babel process. The dashed blocks represent the
optional phases.
48

Merge Input Build Call


Post Reader Process Rules Agent Phase
Assemblies Graph

Dead Code Instrument Dynamic


Build Map Optimizations
Removal Code Proxy Calls

Encrypt Control Flow Encrypt


Renaming Encrypt MSIL
Values Obfuscation Strings

Embed Encrypt
Emit
Assemblies Resources

This diagram is not complete; there are phases not listed above that are used by Bebel as services of the
main phases.

Obfuscation Agent
The Obfuscation Agent consists of a list of tasks that Babel performs against the target assembly type model
to determinate which symbols should not be obfuscated. The Agent prevents symbol names from being
obfuscated according the Common Language Runtimes design rules. Babel is able to run a set of
preconfigured tasks, and they are continuously updated in each new product release. Some of these tasks are
simple—like checking fields of serizializable types. Other tasks are more complex and involve MSIL code
static analysis.

The Agent works to prepare a safer obfuscation process and most of the time the final obfuscated assembly
will run perfectly. Because the Agent can only perform static code analysis, it may not discover types that are
controlled during execution. For example: the names of types, stored into strings that are built at runtime are
opaque to the Agent. Using those strings as parameters of reflection methods impose a restriction on
obfuscating the relative type or member name. Changing those type names will likely break the obfuscated
assembly. For this scenario, XML rules files, combined with Agent, are the recommended solution.

Babel’s Agent is enabled by default and should be left enabled whenever possible. There is generally no
reason to disable the Agent entirely. But if you want, you can arrange an XML Rules file to skip a particular
task from being processed. This scenario is useful when an XML rule is overridden by an Agent task outcome.
Agent tasks run after the Rules processing phase, so any custom XML Rule enforced on a member will be
overridden by the Agent task. The only way to disable agent rules is to define an XML Rule to switch off the
Agent task on that particular member.

For instance, suppose that you want to obfuscate a public type named RedBlackTree. So you prepare a rule
to force Babel to rename the type:

<Rule name="RedBlackTree" feature="renaming" exclude="false">


<Target>Classes</Target>
<Pattern>*.RedBlackTree</Pattern>
<Description>Rename RedBlackTree class.</Description>
</Rule>
49

Then you discover that the type was not renamed because the Agent found that the type is serializable, and
serializable types are not renamed. But suppose you don’t care about serialization and you want that type to
be obfuscated. You can get around this in two different ways. One way is to tell Babel to turn off Agent
analysis with the option –noagent. But this is overkill for our purpose, and the application process might be
broken after the obfuscation because the Agent has not run. The better way, however, is to add a second rule
that forces the Agent to ignore the RedBlackTree type when the serialization task is running.

<Rule name="RedBlackTree agent" feature="agent" exclude="true">


<Pattern>.*RedBlackTree</Pattern>
<Properties>
<TaskNameList>Serializable types</TaskNameList>
</Properties>
<Description>Ignore Serializable types tasks for RedBlackTree.</Description>
</Rule>

In this rule we have two elements that are meant to be explained.

 The feature is set to agent to tell the rule processor that we want the rule to be applied to the
agent.
 The presence of the element Properties with the property TaskNameList that contains the
name of the agent task “Serializable types”. This tells the rule processor that we want to
exclude only the analysis carried on serializable types.

List of available Agent task names:

Task name string Description


Reflected enums Ignore enum types that are consumed by reflection methods
Serializable types Do not rename serializable types
Reflected strings Discover symbol name strings consumed by reflection methods
Reflected types Do not rename types consumed by reflection methods
Type consumed by attributes Do not rename types consumed by attributes
Exposed attributes Ignore symbols that expose specific attributes
XAML analyzer Parse XAML resources to discover types that should not be obfuscated
Table 2 Agent task names
50

Rules File
Babel rules files are XML files that contain information used to customize the obfuscation process. The rules
file consists of a list of rules defined by the XML element <Rule></Rule>. This list is enclosed by the element
<Rules></Rules> that is also the root document element.

Rules Element
<Rules xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0">
<Rule name="rule 1" feature="default" exclude="false">
</Rule>
<Rule name="rule 2" feature="control flow" exclude="true">
</Rule>
</Rules>

The Rules element attribute version is used to define the current schema version and must be set to "2.0".

Attribute Value Required Type Description


version 2.0 Yes System.String Define the current schema version
and must be set to "2.0"
targetAssembly - No System.String Specifies the Assembly name where
the rules will be applied
Table 3 Rules element attributes

Rules are processed in the order they are defined in the XML Rules file and for assemblies optionally
specified by the targetAssembly attribute. Whenever the targetAssembly attribute is not specified the rules are
applied to all assemblies. Each rule is checked against all the assembly symbols: types, methods, events,
properties and fields. If a symbol name matches a rule, the obfuscation action is taken according to the value
(true or false) assigned to the attribute exclude:

Rule Element
The Rule element is suited to configure an obfuscator feature targeted by the attribute feature.

<Rule name="my rule" feature="default" exclude="false" applyToMembers="false">


...
</Rule>

The Rule element accepts the following attributes:

Attribute Is Mandatory Default Descryption


name Yes - Friendly rule name
exclude Yes - Whether to exclude all the symbols that match
the rule.
feature No default (renaming) The obfuscator feature name as given in Table 4
Obfuscator feature table
applyToMembers No False Whether to apply the rule to all members of a
symbol that match the rule itself.

The feature attribute defines the obfuscator feature on which the rule acts. The name and exclude attributes
are mandatory. The feature attribute is optional, and if not specified refers to the default feature (renaming).
51

The obfuscator feature strings are fixed. All the supported feature names are listed in the following table:

Feature Description
all All obfuscator features
default Member names obfuscation
agent Obfuscation agent
control flow Control flow obfuscation
dead code Dead code removal
dynamic proxy Dynamic proxy calls
merge Assembly merge
msil encryption MSIL encryption
msil encryption get stream Declare get source stream method
renaming Member names obfuscation
resource encryption Embedded resources encryption
string encryption String encryption
string encryption encrypt method Defines string encrypt method
string encryption decrypt method Defines string decrypt method
value encryption Inline values and arrays encryption
instrumentation Code instrumentation
instrumentation on entry method Defines code instrumentation on entry method
instrumentation on exit method Defines code instrumentation on exit method
instrumentation on exception method Defines code instrumentation on exception method
optimizations Metadata optimizations
value encryption Encrypt inline values and arrays
xaml XAML BAML obfuscation
Table 4 Obfuscator feature table

When there are two or more rules that match a symbol name and targeting the same feature in the same XML
file, the first rule declared in the file is taken into account.

! NOTE
Babel is able to process multiple XML Rules files. When more than one Rules file is passed into the
command line, the rules declared in each file can override an enforced rule declared in a previously
processed file. So the order in which the --rule option is passed to the command line is important.

Any Rule element has other child elements: Access, Target, Pattern, HasAttribute, Properties and Description.
The Pattern element is mandatory, whereas the others are optional.

<Access> - Specifies the symbol visibility for the rule. Possible values are: All or any combination of Public,
Protected, Internal, and Private. If the element is not present the default value All is used.

<Target> - Specifies which kind of symbol should be checked. Admitted values are: All or any combination
of Classes, Delegates, Structures, Interfaces, Enums, Events, Methods, Properties, Fields, StaticFields and
Resources. If the element is not present the default value All is assumed.

<Pattern> - Can be any wildcard expression or regular expression. The Boolean attribute isRegEx states
whether the pattern is a regular expression. If a regular expression is used, it’s good practice to enclose the
regular expression definition string in a CDATA section, ex.:

<Pattern isRegEx="true"><![CDATA[^Properties.*]]></Pattern>

<HasAttribute> - Specifies a list of fully-qualified type attributes. If the target has at least one of these
attributes, the rule matches. This element may have the Boolean attribute onEnclosingType. If set to false, the
attribute is checked on the target symbol itself. If the attribute is true, the attribute is checked on the target
symbol enclosing type instead of the symbol itself.
52

<HasAttribute onEnclosingType="true">System.SerializableAttribute</HasAttribute>

<Properties> Defines a collection of elements used to customize the feature behavior. Each feature may
support a set of property elements. For instance, the following rule sets two properties of the msil encryption
feature: Cache and MinInstructionCount.

<Rule name="DataWriter" feature="msil encryption" exclude="false">


<Target>Methods</Target>
<Pattern>SQLUtils.DataWriter::*</Pattern>
<Properties>
<Cache>true</Cache>
<MinInstructionCount>6</MinInstructionCount>
</Properties>
<Description>Encrypt all methods of the DataWriter class.</Description>
</Rule>

Follow the list of property elements supported by each feature:

Feature Element Type Description


agent TaskNameList System.String List of comma separated
agent task names.
merge Internalize System.Boolean If true, all types that match
the rule have their visibility
changed to internal.
renaming Internalize System.Boolean If true, all types that match
the rule have their visibility
changed to internal.
string encryption MinInstructionCount System.Int32 Threshold for method
minimum instruction count.
ManInstructionCount System.Int32 Threshold for method
maximum instruction count.
control flow IlIterations System.Int32 The number of iterations to
use in the control flow
obfuscation algorithm.
EmitIvalidOpcodes System.Boolean If true, invalid op-codes are
inserted into the method
definition.
ChangeIfStatement System.Boolean If true, obfuscate if
statements.
AddSwitchStatement System.Boolean If true, switch statements are
inserted into method
definition.
ScrableControlFlow System.Boolean Whether to produce
spaghetti code inserting
irrelevant branches.
MaxSwitchTargets System.Int32 Set the maximum number of
switch case targets in the
switch control flow
obfuscation.
HideCaseConstantExpressions System.Boolean If true, hide the calculated
constant values in switch
control flow obfuscation.
AddMethodToken System.Boolean If true, load method token
instructions are inserted
inside the method body.
StackUnderflow System.Boolean Whether to enable stack
underflow instructions
generation
53

UseValueEncryption System.Boolean Whether to encrypt switch


jump table values (available
only when value encryption
is enabled).
RandomCall System.Boolean Whether to generate random
calls jump table (available
only when switch control
flow is enabled).
MinInstructionCount System.Int32 Threshold for method
minimum instruction count.
ManInstructionCount System.Int32 Threshold for method
maximum instruction count.
msil encryption Cache System.Boolean If true, the encrypted method
is cached so that the
compilation process is run
only the first time the method
is used.
MinInstructionCount System.Int32 Threshold for method
minimum instruction count.
ManInstructionCount System.Int32 Threshold for method
maximum instruction count.
Source System.String MSIL-encrypted data source
name
dead code - -
resource encryption - -
optimizations ClassSealing System.Boolean Whether to enable class
sealing optimization
UnwantedAttributes System.Boolean Whether to enable removal
of unwanted attributes
EnumRemoval System.Boolean Whether to enable removal
of System.Enum type
ConstRemoval System.Boolean Whether to enable removal
of constant fields
Table 5 Feature properties

<Description> - Any useful rule description

The following example shows the content of an XML rule files.

<Rules xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0">
<Rule name="Properties types" exclude="true">
<Pattern isRegEx="false">*Properties*</Pattern>
<Description>Do not obfuscate Properties namespace symbols.</Description>
</Rule>
<Rule name="Serializable types" feature="default" exclude="true">
<Target>Fields, StaticFields</Target>
<Pattern><![CDATA[*]]></Pattern>
<HasAttribute onEnclosingType="true">
System.SerializableAttribute
</HasAttribute>
<Description>Do not obfuscate fields of serializable types.</Description>
</Rule>
</Rules>

The first rule tells Babel to not obfuscate any symbols inside the Properties namespace or whatever symbol
contains Properties in its fully-qualified name. The second rule tells Babel to not obfuscate fields of types that
are declared as serializable. The System.SerializableAttribute attribute presence is checked on the
field enclosing type because the XML attribute onEnclosingType is set to true.
54

Custom Attributes
Babel supports declarative obfuscation using custom attributes provided by the .NET Framework 2.0 and
attribute types declared in the Babel.Code.dll assembly. This section explains the usage of custom attributes
to customize the obfuscation process.

System.Reflection.ObfuscateAssemblyAttribute
This assembly-level attribute instructs Babel to use obfuscation rules reserved to private assemblies. A private
assembly is an assembly that will not be used as a library: no other software components will use the
assembly. Private assemblies are fully obfuscated by Babel and will use obfuscation rules to rename public
symbols.

The following code example shows how to mark an assembly private with the ObfuscateAssemblyAttribute.

using System;
using System.Reflection;

[assembly: ObfuscateAssembly(true)]

System.Reflection.ObfuscationAttribute
This attribute is used on assembly members: types, method, events, properties and fields to configure the
action taken for a specific obfuscation feature. This attribute has a string Feature property. This property is
used to map the string value to a specific obfuscator feature. The default value of Feature property is “all”.
Babel uses “all” to map the complete set of features and “default” to map the renaming feature. The complete
set of feature names are the same supported by rules files and are listed in Table 2--Obfuscator feature table.
The ObfuscationAttribute has a three other Boolean properties: Exclude, ApplyToMembers and
StripAfterObfuscation. They have their default value set to true. The Exclude property indicates whether the
obfuscation feature should be excluded for the associated member. The ApplyToMembers property specifies
whether the action taken by the obfuscator for the associated type should be applied to all its members. The
StripAfterObfuscation property specifies whether the attribute should be removed after processing.

The following code example shows how ObfuscationAttribute can be used to target a method for MSIL
encryption:

using System;
using System.Reflection;

[Obfuscation(Feature = "msil encryption", Exclude = false)]


public string RandomString(int length, string characters)
{
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
int inx = _rnd.Next(characters.Length);
sb.Append(characters[inx]);
}
return sb.ToString();
}
55

Babel.Code.dll Assembly
A set of custom attributes are available in the Babel.Code.dll assembly. This assembly is located in the Babel
installation folder. The available attribute are:

Attribute type Description


DecryptStringMethodAttribute Used to design the custom decryption string method.
EncryptStringMethodAttribute Used to design the custom encryption string method.
EncryptStringsAttribute Controls the encryption of string actions on the associated method.
ObfuscateAttribute Controls the renaming of the associated member.
Table 6 Custom attributes found in Babel.Code.dll

The DecryptStringMethodAttribute and EncryptStringMethodAttribute are used to specify the custom string
decryption and encryption methods and are explained in the String Encryption section.
The EncryptStringsAttribute targets methods and it controls the action taken by the obfuscator for the “string
encryption” feature. This attributes has an Encrypt boolean property. If it is set to true all the strings in the
method will be encrypted. The ObfuscateAttribute targets all members and it controls action taken for the
“renaming” feature. This attribute has a boolean Obfuscate property that if set to true tells Babel to rename the
associated member. The EncryptStringsAttribute and ObfuscateAttribute can be replaced by the
System.Reflection.ObfuscationAttribute.This should be the preferred attribute choice when you want to
configure the action taken by the obfuscator.

All these attributes and the Babel.Code reference, are removed from the assembly once they are processed
by the obfuscator.
56

Merge and Embed


Assemblies
Babel Obfuscator can merge and embed multiple .NET assemblies into the target assembly. This will simplify
the application deployment and increase the protection. Babel is able to merge also WPF and Silverlight
assemblies although with some limitation.
In this section we will see how to merge and embed multiple assemblies with the target assembly and how to
use XML rules to change the default merging behavior.
57

Assembly Merging
To merge multiple assemblies with the target assembly, just enter at the command line the file names of the
assemblies that need to be merged after the name of the target assembly:

babel.exe myapp.exe graphics.dll engine.dll

Where the first assembly in the list: myapp.exe is the target or primary assembly, whereas graphics.dll and
engine.dll are the assemblies that will be merged into the primary assembly.

Babel takes the list of input assemblies after the target assembly and merges them into the target assembly.

babel.exe <primary assembly source> [<other assemblies>...] [options]

There are several options that can be used to configure merging:

--[no]copyattrs
When enabled, force Babel to copy all assembly-level attributes into the primary assembly. Any duplicate
attribute will be discarded. This option is enabled by default.

--[no]internalize
When enabled, modifies the visibility of all the merged assembly types from public to internal. Because
referenced types are always public, lowering their visibility to internal in the merged assembly ensures name
mangling, improving the overall obfuscation statistics.
This option is disabled by default because changing type visibility will prevent the merged types from being
consumed outside of the primary assembly. Any way you can enable this option if the merged types are used
only by the primary assembly.

These two options act globally for all the types declared inside the assemblies that are to be merged. If you
want to selectively merge or internalize types, you can use XML rules files. With rules files you can choose
types that will be merged and internalized by simply making a regular expression or a wildcard expression for
the merge feature.

For instance, the following rules merge and internalize all the types coming from the Utilities namespace,
excluding all the other types from being merged:

<Rule name="Utilities namespace" feature="merge" exclude="false">


<Pattern>Utilities.*</Pattern>
<Properties>
<Internalize>true</Internalize>
</Properties>
<Description>
Merge and internalize all type in Utilities namespace.
</Description>
</Rule>
<Rule name="exclude all the other types" feature="merge" exclude="true">
<Pattern>.*</Pattern>
</Rule>

Babel processes rules in the order in which they are declared in the rules file. So if the first rule has a mach
for a given type, the second one will not be evaluated. Otherwise, if the first rule does not have a mach, the
second one will certainly mach, because it matches all the types and the type matched will not be merged
because the exclude property is set to true.

Selectively merging types with XML rules might break the target assembly because Babel does not perform
any check on the type integrity of the resulting assembly. So it is recommended that you run the peverify.exe
tool on the target assembly just to be sure that the rules have not left out any used type.
58

Merging Silverlight and WPF assemblies


Babel is able to merge Silverlight and WPF assemblies containing XAML and BAML resource streams.
Generally WPF and Silverlight applications contain XAML and BAML resources that enclose the identity of the
merged assemblies. Babel is able to de-serialize the resources, modify the assembly identities, and then re-
serialize them. There is only a limitation in this operation. Babel cannot merge two assemblies that contain the
same resource URI inside the XAML/BAML resource dictionary.

For instance, consider we want to merge two WPF assemblies MyApp.exe and Chart.dll. Both assemblies will
have their WPF resources contained in an embedded resource dictionary named MyApp.g.resources and
Chart.g.resources respectively. Suppose now that the two assemblies define a WPF custom control with its
template stored into Themes\generic.xaml file. This file is used as a fallback to define the default style for
most controls. In this scenario Babel will have to merge the BAML stream Themes/generic.baml included in
Chart.g.resources resource dictionary into the MyApp.g.resources resource that already contains a BAML
stream with the same name. This scenario is not handled and the merge will end with the following warning:

Warning [MG0003]: Resource data 'themes/generic.baml' into Chart.g.resources has already


been added.

The resulting assembly may not work expecially when the resources files are different.

Babel can merge also assemblies inside a Silverlight XAP package with the target assembly. When
obfuscating a XAP package, the target assembly is the entry point assembly defined in the AppManifest.xaml
file. The assemblies that will be merged are listed at the command line after the XAP file name:

babel.exe myapp.xap graphics.dll engine.dll

Where myapp.xap is the XAP package containing the target assembly and the two merged libraries:
graphics.dll and engine.dll. Note that in the resulting XAP file the two merged library will be removed.
59

Assembly Embedding
Babel Obfuscator can embed multiple assemblies into the main application reducing the overall size of the
deployed assembly. The embedded assemblies are not obfuscated. If you need to protect the embedded
assemblies you should obfuscate them first.

Embedded assemblies are stored into managed resources as compressed and encrypted data. You can
selectively compress and/or encrypt an embedded assembly by using XML rules files.

The following image shows a sample application EmployerTracker.exe after obfuscation. The referenced
DLLs EmployeeTracker.Common.dll, EmployeeTracker.EntityFramework.dll, EmployeeTracker.Fakes.dll and
EmployeeTracker.Model.dll were embedded into resources.

The embedded assemblies don’t need to be deployed; they are loaded at runtime directly from memory.
To embed an assembly inside the primary assembly, enter at the command line the --embed switch followed
by the assembly file name you want to embed:

babel.exe EmployeeTracker.exe --embed EmployeeTracker.Common.dll -–embed


EmployeeTracker.EntityFramework.dll --embed EmployeeTracker.Fakes.dll --embed
EmployeeTracker.Model.dll

Babel will compress and encrypt all the assemblies inside managed resources. These assemblies will be
loaded dynamically at runtime when the application will requires the access to any of the types defined in the
embedded assemblies. Compression and encryption can be selectively turned on or off by using XML rules
files targeting the embed feature. Turning off compression and encryption may significantly reduce the
application startup time by improving performance respect to overall application size on disk.

For instance if we want to encrypt the assembly EmployeeTracker.EntityFramework.dll without enabling


compression for that assembly and we want to disable both encryption and compression for
EmployeeTracker.Fakes.dll we must define the following XML rules:
60

babelRules.xml

<?xml version="1.0" encoding="utf-8" ?>


<Rules version="2.0">
<Rule name="embed EF" feature="embed" exclude="false">
<Target>Assembly</Target>
<Pattern>EmployeeTracker.EntityFramework.dll</Pattern>
<Properties>
<Encrypt>true</Encrypt>
<Compress>false</Compress>
</Properties>
</Rule>
<Rule name="embed fakes" feature="embed" exclude="false">
<Target>Assembly</Target>
<Pattern>EmployeeTracker.Fakes.dll</Pattern>
<Properties>
<Encrypt>false</Encrypt>
<Compress>false</Compress>
</Properties>
</Rule>
</Rules>

Finally we have to pass the babelRules.xml at command line as follows:

babel.exe EmployeeTracker.exe --embed EmployeeTracker.Common.dll -–embed


EmployeeTracker.EntityFramework.dll --embed EmployeeTracker.Fakes.dll --embed
EmployeeTracker.Model.dll --rules babelRules.xml

We can see the encryption and compression flags for each embedded assembly at the Babel output statistics:

Embed Assemblies phase, elapsed time 00.868s


Number of embedded assemblies: 3
EmployeeTracker.Common.dll (compress=True , encrypt=True )
EmployeeTracker.EntityFramework.dll (compress=False, encrypt=True )
EmployeeTracker.Fakes.dll (compress=False, encrypt=False)
EmployeeTracker.Model.dll (compress=True , encrypt=True )

NOTE: The embedding of assemblies is not supported on all .NET platforms. To see the platforms where
assembly embedding is available, please refer to the Technology Matrix.
61

Symbols Renaming
Babel Obfuscator is able to rename all classes, methods, properties, events and fields to short names using
custom Unicode characters or standard ASCII codes. This will makes the decompiled output more difficult to
understand and will also reduce the size of your assembly files. In this section we will see how to setup
symbols renaming, Unicode normalization and the XML map files produced during the obfuscation process.
We will also see how to rename symbols inside BAML and XAML code when obfuscating WPF and Silverlight
applications.
62

Symbols Renaming
Babel can mangle the names of namespaces, types, methods, properties, events and fields, changing their
names into a combination of alphabet character or unprintable Unicode symbols. The original symbol name is
lost and is impossible to recover the meaning of the obfuscated member. This makes code understanding and
reverse engineering extremely difficult.

You can choose from two different renaming conventions: alphabet characters or unprintable Unicode
symbols. Both minimize the number of character symbol used, reducing the overall metadata size and load
time. Babel uses the Unicode renaming schema as default, but you can switch to alphabet character set by
specifying the option --nounicode in the command line.

There are several options available to configure the Renaming process:

--types
Will enables type renaming.

--methods
Will enables method renaming.

These options can be negated to disable renaming. You might consider to disable type renaming by using the
switch --notypes or -not when debugging obfuscation issues relating to renaming.

--overloaded
This option enables overloading renaming. With overloading renaming it is possible to assign the same name
to different methods.

--virtual
Will enables the renaming of virtual symbols (methods, properties, events).

--flatns
The flat namespace option controls the namespace renaming. When this option is enabled, the types inside
each namespace are collapsed into the global namespace.

--xaml
This option enables the renaming of types and members used inside the XAML and BAML code.

--namelength <n>
Set the minimum name length for each symbol. Increasing this value will produce longer names more difficult
to read at the expense of an increase of the assembly size.

! NOTE
Externally-visible symbols will not be renamed by Babel unless you specify a custom rule to force that. To
increase the overall number of members obfuscated, considers lowering the visibility of your public types to
internal.
63

The following picture shows an assembly before and after name obfuscation using Unicode normalization.

Before renaming After renaming


64

Unicode Character Set


It is possible to specify the character set to use when Unicode normalization is performed.
The option --unicode accepts the optional parameter [char set] that represents a set of Unicode characters
that babel will use to generate obfuscated names. The character set can be entered specifying the comma
separated values of each Unicode character or by entering ranges of characters where the range of Unicode
values is given by the following expression:

<lower bound character> – <upper bound character>

Where <lower bound character> and <upper bound character> can be represented as hexadecimal, decimal
number or character. A mix the two forms can be used to realize a complex obfuscation Unicode character
set.

Examples:

Introducing CR (13) and LF (10) in obfuscated names

babel.exe myapp.exe –-unicode 10,13,a-z

Change to Unicode Chinese character set:

babel.exe myapp.exe --unicode 0x4E00-0x4FFF

Refer to the Unicode Character Ranges table for more customizations.


Note that when using custom character set is not always possible to generate an XML map file.

Overloaded Renaming
With overloaded renaming, the same name is used to rename methods with different signatures as long as it
is allowed by .NET Framework design rules. This makes it even more difficult for a hacker to reverse engineer
the code. Babel also renames overloads when only the method return type differs, making it impossible to
entirely decompile the code to high-level languages like C# and VB.NET, in which overloading the return type
is not permitted.

Source Overloaded Renaming


65

XAML and BAML Obfuscation


Silverlight and Windows Presentation Foundation (WPF) applications uses XAML declarative markup
language, and BAML (compiled XAML), to instantiate types defined into the assembly. Babel Obfuscator
version 3.5 was one of the first obfuscator able to analyze the XAML stream in order to obfuscate Silverlight
application successfully.

Babel Obfuscator now can parse XAML and BAML resources and rename all the members referenced into
the XAML (BAML) code to produce a better obfuscation increasing the percentage of obfuscated symbols.
This also makes your XAML code more difficult to read. Babel is also able to merge into a single assembly file
multiple assemblies containing XAML (BAML) resources.

The XAML and BAML symbols renaming, is enabled by entering the --xaml switch at the command line. This
switch has additional optional parameters, as we will see later, which can be used to enhance the XAML
(BAML) obfuscation. In order to fully obfuscate all the public symbols referenced into the XAML (BAML) code,
just add to the command line the --xaml option. Babel will obfuscate all public symbols referenced into the
XAML or BAML code.

babel.exe myapp.exe --xaml

When obfuscating XAP packages, this option will force renaming of public XAML symbols defined into the
entry assembly preserving the names of the public symbols defined into referenced assemblies. Presently is
not possible to use public obfuscation driven by XML map files within a XAP package. Anyway Babel is able
to obfuscate each assembly separately or even merge multiple assemblies inside the XAP package into a
single obfuscated assembly.

It is possible to configure additional parameters by including optional key-value pairs after the --xaml switch in
which the key is passed as a parameter with its corresponding value:

--xaml [<key>=<value>]

Admitted key value pairs are:

Key Value Default Description Available


Manual On/Off Off Whether to use manual symbol renaming BAML/XAML
Keys On/Off Off Whether to enable renaming of static resource BAML/XAML
dictionary keys
Strip On/Off Off Whether to strip line information/white spaces in BAML/XAML
BAML/XAML

Manual symbol renaming is disabled by default. With manual symbol renaming disabled, Babel will obfuscate
all public members that are found to be referenced inside the XAML or BAML code. This is a convenient
option that minimizes the configuration required by the user to achieve a better obfuscation result. Sometimes
it is necessary to fine tune the obfuscation process by choosing carefully the public members that have to be
obfuscated. In this scenario it is better to switch on manual renaming and use quick rule or XML rules files to
target those members.

Keys parameter when enabled will allow Babel to rename static resource key names. This will increase the
obfuscation of XAML/BAML code.

Strip parameter will remove all line information from XAML/BAML code making the XAML stream difficult to
analyze.
66

Silverlight XAML Obfuscation


XAML renaming ensures a high percentage of symbol renaming and therefore helps to improve the overall
obfuscation. Babel it’s also able to strip spaces and line feeds from the XAML code reducing the size of
embedded resources. The following section shows the XAML code of a Silverlight 4.0 application before and
after obfuscation produced by Babel using XAML renaming.

MainPage.xaml content before obfuscation (2524 bytes):

<sl4:ChildWindow x:Class="SL4ObfTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:SL4ObfTest.Controls"
xmlns:sl4="clr-namespace:SL4Controls;assembly=SL4Controls" mc:Ignorable="d"
Height="400" Width="600"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<sl4:ChildWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</sl4:ChildWindow.Resources>
<sl4:ChildWindow.Header>
<TextBlock Text="{Binding NoteTitle}" />
</sl4:ChildWindow.Header>
<sl4:ChildWindow.Content>
<Grid>
<controls:TiledBackground SourceUri="/SL4ObfTest;component/Images/backgroundtexture.png" Opacity="0.7" />
<Image Source="/SL4ObfTest;component/Images/backgroundshadow.png" Stretch="Fill" />
<Grid x:Name="LayoutRoot">
<TextBlock FontSize="18" FontWeight="Bold" Foreground="White"
Text="{Binding Title}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap" Height="28" Width="276" Margin="6,6,316,344" />
<sl4:ChildWindow Margin="20,40,350,200">
<sl4:ChildWindow.Header>
<TextBlock Text="{Binding NoteTitle}" />
</sl4:ChildWindow.Header>
<sl4:ChildWindow.Content>
<StackPanel Orientation="Vertical" Margin="8">
<TextBlock Text="{Binding RandomQuote}" Margin="0,0,0,5" TextWrapping="Wrap" />
</StackPanel>
</sl4:ChildWindow.Content>
</sl4:ChildWindow>
<Slider Height="22" HorizontalAlignment="Left" Margin="256,40,0,0" Name="slider1" VerticalAlignment="Top"
Width="120" Maximum="100" />
<sl4:ProgressButton Height="120" Width="120" Margin="256,40,224,240" Value="{Binding ElementName=slider1,
Path=Value}"/>
</Grid>
</Grid>
</sl4:ChildWindow.Content>
</sl4:ChildWindow>

And after obfuscation (1656 bytes):

<_babel0:a x:Class="a.e" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Height="400" Width="600"
DataContext="{Binding b, Source={StaticResource a}}" xmlns:_babel0="clr-
namespace:a"><_babel0:a.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary
Source="Skins/MainSkin.xaml"/></ResourceDictionary.MergedDictionaries></ResourceDictionary></_babel0:a.Resources><_babel0:a.a>
<TextBlock Text="{Binding b}"/></_babel0:a.a><_babel0:a.Content><Grid><_babel0:d Opacity="0.7"
_babel0:d.SourceUri="/SL4ObfTest;component/Images/backgroundtexture.png"/><Image
Source="/SL4ObfTest;component/Images/backgroundshadow.png" Stretch="Fill"/><Grid x:Name="a"><TextBlock FontSize="18"
FontWeight="Bold" Foreground="White" Text="{Binding a}" VerticalAlignment="Center" HorizontalAlignment="Center"
TextWrapping="Wrap" Height="28" Width="276" Margin="6,6,316,344"/><_babel0:a Margin="20,40,350,200"><_babel0:a.a><TextBlock
Text="{Binding b}"/></_babel0:a.a><_babel0:a.Content><StackPanel Orientation="Vertical" Margin="8"><TextBlock Text="{Binding
c}" Margin="0,0,0,5" TextWrapping="Wrap"/></StackPanel></_babel0:a.Content></_babel0:a><Slider Height="22"
HorizontalAlignment="Left" Margin="256,40,0,0" Name="b" VerticalAlignment="Top" Width="120" Maximum="100"/><_babel0:b
Height="120" Width="120" Margin="256,40,224,240" _babel0:b.a="{Binding ElementName=b,
Path=Value}"/></Grid></Grid></_babel0:a.Content></_babel0:a>

The options used to produce this result were:


67

--xaml keys=on --xaml strip=on

Note that in the obfuscated XAML code, the names of all members defined into the target assembly as well as
dictionaries names have been renamed using ASCII character set.

Obfuscating Windows Phone 7 Applications


This sample will show how to setup obfuscation in a Visual Studio 2010 project for a Windows Phone 7
Silverlight project using XAML code renaming.

To obfuscate a Silverlight XAP package build for Windows Phone 7 from within Visual Studio 2010, just edit
the Visual Studio project file by inserting the necessary Babel task XML instructions to configure the
obfuscation process:


<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for
Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0, Culture=neutral,
PublicKeyToken=138d17b5bd621ab7" />
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
<Babel InputFile="$(OutputPath)$(ProjectName).xap"
OutputFile="$(OutputPath)$(ProjectName).xap"
GenerateDebug="true"
FlattenNamespaces="true"
StringEncryption="true"
ControlFlowObfuscation="true"
ObfuscateXaml="strip=on;keys=on">
</Babel>
</Target>
<ProjectExtensions />
68

</Project>

The first XML element to insert is the UsingTask instruction that maps the Babel task element to the assembly
Babel.Build installed into the GAC. The Babel task element was inserted as a child of the AfterBuild Target
element to ensure that the obfuscation is performed as soon after the build process terminates.

Then set the InputFile and the OutputFile properties to the path of the XAP file produced during the build:
$(OutputPath)$(ProjectName).xap. Babel will obfuscate in place the XAP package, facilitating the deployment
to the device.
69

Control Flow
Obfuscation
Control flow obfuscation consists of changing the execution path of a method. Babel can make if statements
more complex to read, insert a number of irrelevant branches, add multiple switch instructions without
changing the behavior of the method so that is very difficult to analyze after decompilation.
70

Basic Control Flow Obfuscation


Basic control flow obfuscation is enabled with the command line option --controlflow. When enabled, Babel
changes the execution path of a method inserting a number of irrelevant branches so that, although the
behavior of the method is not changed, it is very difficult to analyze after decompilation. Consider the following
example that shows a method before and after control flow obfuscation.

Before control flow obfuscation After control flow obfuscation

Note: after control flow obfuscation is


performed, it is no longer possible to
reconstruct the original if-else and loop
clause for disassembly inside .NET
Reflector and only the IL listing can be
displayed.

The number of jumps inserted by Babel can be changed in a certain amount changing the number of
iterations performed by the control flow obfuscation algorithm. This parameter is configured by the command
line option switch –iliteration <n>. Increasing the <n> value may result in an increase of the number of
branches inserted.

The <n> value does have an upper limit where the control flow cannot be altered anymore by the algorithm.
This limit depends on the method control flow structure and can be different according to the particular
method considered. This means that increasing <n> does not always result in an increased number of jumps.
71

The following graphs show an average number of jumps inserted (vertical axes) varying with the number of
iterations <n> imposed (horizontal axes) for two different assemblies. The first assembly with 1,202 methods
processed is shown on the left, whereas the second assembly with 2,596 methods processed is on the right.
The trend dash lines show that the optimum iteration value is about 3, which is also the default value.

1,202 methods scrambled 2,596 methods scrambled


16 16
14 14
12 12
10 10
8 8
6 6
4 4
2 2
0 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Average number of jump inserted Delta Average number of jump inserted Delta

It is not recommended to increase the <n> parameter over 6, as higher values will scramble the code more,
causing the overall execution time to increase.

Enhanced Control Flow Obfuscation


The Professional and Enterprise versions have an enhanced control flow obfuscation that is able to scramble
the method flow graph with the insertion of nested switch instructions and also make structural code changes.
This makes it more difficult to analyze the code and stop, or at least makes incorrect the representation of the
underlying high-level IL code produced by reverse engineering tools.

The enhanced control flow obfuscation is active by default when a Professional or Enterprise license is
available. In this case the controlflow option enables the generation of the enhanced control flow obfuscation
that is IL verifiable.

The user can configure additional parameters to customize the code generation by passing additional key-
value pairs to the controlflow command line option:

--controlflow [<key>=<value>]

Admitted key value pairs are:

Key Value IL Verifiable Description


goto On/Off  Whether to insert irrelevant branches
switch On/Off  Whether to enable switch scrambling
case On/Off  Whether to hide case constants
if On/Off  Whether to enable if scrambling
call On/Off  Whether to enable random calls
Value On/Off  Whether to use value encryption
token On/Off  Whether to enable emission of method tokens
underflow On/Off Whether to enable stack underflow

! NOTE
Not all the transformations performed during control flow obfuscation are safe and makes your assembly IL
verifiable.
72

Before control flow obfuscation After enhanced control flow obfuscation (ILSpy)

Invalid Op-Codes
Invalid op-codes are byte codes not recognized by the runtime as valid MSIL instructions that Babel inserts in
each method to prevent the disassembler from decompiling the method. Invalid op-codes are not managed
properly by disassemblers like .NET Reflector, while the ILDASM disassembler can list the MSIL even with
the presence of invalid bytes. Therefore it is recommended to disable the ILDASM tool with the option –
noildasm whenever possible.

The following table shows, on the left, the .NET Reflector method IL listing after obfuscation with invalid op-
codes. On the right side the same method is represented by ILDASM disassembler.
73

.NET Reflector C# and IL code listing ILDASM code listing

The unused instructions at offset 2, 3 and 17 that


ILDASM output in the code disassembly reflect the
inserted invalid op-codes.

The number of iteration used in the control flow algorithm as well as the invalid op-codes emission can be
configured using XML rules. There are two properties available in the control flow feature that are applied on
each method that match the rule: IlIterations and EmitInvalidOpcodes. The first is a positive integer and sets
the number of iterations for the control flow algorithm. The latter is a Boolean value and is used to enable the
emission of invalid op-codes.

Invalid op-code emission should not be performed if the obfuscated assembly targets x64 operating systems
(see Obfuscating x64 Assemblies).
74

Encryption and
Protection
Babel Obfuscator can encrypt the strings and embedded resources inside the assembly. It is also able to
encrypt the method MSIL code.
String encryption prevents an attacker for searching inside your assembly strings that could help in identifying
sensitive code. There are two ready-made string encryption algorithms available, plus there is the possibility
to write and plug inside the obfuscation process your custom string encryption algorithm.
With MSIL encryption, Babel can hide the original method code to MSIL decompilers. The encrypted methods
are decrypted at runtime only when they are accessed and stay in memory only for the time needed to the
execution and then discarded. This ensures that the method code cannot be modified in memory. The runtime
compilation also makes the method code safe against tampering. MSIL encryption is a powerful protection
tools and it is completely managed solution. Anyway the process of decryption and runtime execution involves
reflection and this has impact on the performance. In this section we will see how to enable string and
resource encryption and get the best from MSIL encryption without losing too much in terms of execution
speed.
75

MSIL Encryption
The MSIL encryption provided by Babel is a completely managed solution. This means that the encrypted
methods are not replaced by native code targeting a particular platform. The managed method encryption
ensures that the cross platform nature of the .NET Framework is not compromised. Moreover, the runtime
compilation of encrypted methods allows the Just-In-Time (JIT) compiler to optimize code for the target CPU.
When a method is encrypted, its code is replaced by a call to a stub method that decrypts and compiles a
dynamic method (System.Reflection.Emit.DynamicMethod) at runtime. The original MSIL code is compressed
and encrypted into the assembly resources. Babel ensures tamper protection on the encrypted method
resource when the original assembly is strong-name signed.

When a method is encrypted, its MSIL code is replaced by a call to a stub method that ensures decryption,
runtime compilation and execution of the dynamic method. The process of decryption, compilation and
execution of the dynamic method is much slower than the original method execution, so the user must choose
carefully the list of methods to encrypt. The user can select a method to encrypt with XML rules files or by
applying on the method the System.Reflection.ObfuscationAttribute attribute. Rules files are more flexible and
allow the user to specify encryption options that are not supported by the custom attribute.
For instance, suppose you have a type named Rgb that encapsulates RGB color components, and you want
to encrypt all its methods. If the Rgb class contains few methods you can apply to each method the
System.Reflection,ObfuscationAttribute as follow:

namespace Utilities
{
public class Rgb
{
byte _r; byte _g; byte _b;

public Rgb(byte r, byte g, byte b)


{
_r = r; _g = g; _b = b;
}

public UInt32 Value


{
[Obfuscation(Feature = "msil encryption", Exclude = false)]
get
{
return ToUint32();
}
}

[Obfuscation(Feature = "msil encryption", Exclude = false)]


public UInt32 ToUint32()
{
return (UInt32)((_r << 16) | (_g << 8) | _b);
}

[Obfuscation(Feature = "msil encryption", Exclude = false)]


public static UInt32 ToUint32(Rgb rgb)
{
return rgb.ToUint32();
}
}
}

When the number of methods on the Rgb type becomes significantly large it is better to define a custom XML
rule:

<Rule name="Rgb" feature="msil encryption" exclude="false">


76

<Target>Methods</Target>
<Pattern>Utilities.Rgb::*</Pattern>
<Description>Encrypt all methods of Rgb class.</Description>
</Rule>

The above rule defined will encrypt all the methods of Rgb class.

Encrypting too many methods may results in slowing down excessively the application during execution. In
this scenario the developer can tune the number of method that will be encrypted using custom properties
enabled for the specific feature “msil encryption”.
These custom properties are:

 MinInstructionCount
 MaxInstructionCount
 Cache
 Source

The MinInstructionCount element sets the lower limit for the number of MSIL instuctions that a method must
have to be encrypted. Conversely, the MaxInstructionCount element sets the upper limit for the number of
MSIL instuctions that a method must have to be encrypted. The Cache element contains a boolean value, and
when enabled, all the DynamicMethod attributes that match the rule are cached into memory so that the
compilation is performed only the first time the method is called. This optimization is enabled by default. The
user may decide to disable caching to ensure that the method is discarded after being used in order to free
memory resources.

<Rule name="Rgb" feature="msil encryption" exclude="false">


<Target>Methods</Target>
<Pattern>Utilities.Rgb::*</Pattern>
<Properties>
<Cache>true</Cache>
<MinInstructionCount>5</MinInstructionCount>
<MaxInstructionCount>50</MaxInstructionCount>
</Properties>
<Description>Encrypt methods of Rgb class.</Description>
</Rule>

The Source element contains a string value and its use will be described in the Customize MSIL Encryption
section.
77

The following screenshot illustrates the changes introduced by MSIL encryption:

Before MSIL encryption After MSIL encryption

Note that all the code inside the method has been replaced by a single call to an internal method that
performs decryption and code compilation of a System.Reflection.Emit.DynamicMethod object equivalent to
the original method. This encryption technique has some limitations and not all methods can be encrypted.
The methods that do not support MSIL encryption are:

• Instance constructor
• Generic methods
• Methods that uses generic non-instance types
• Methods with ref or out parameters

If the user tries to obfuscate such methods, Babel will raise a warning and the method will not be encrypted.
These constraints constitute a restriction on the methods that can be encrypted, but as the method encryption
is not intended to be used extensively on the target assembly, this limitation is not very important. The
developer should encrypt only highly sensitive methods. A few examples of methods you may want to encrypt
are:

• License file parsing


• Activation key validation
• Proprietary algorithms

Most of the time, these methods can be arranged so that Babel can successfully perform MSIL encryption.
Note that since Miscrosoft provides different implementation of DynamicMethod depending on the .NET
Framework technology, MSIL encryption is supported only on .NET Framework 2.0 and later (see Technology
Matrix).
78

String Encryption
Babel is able to encrypt so-called User Strings embedded into a managed assembly. User Strings are all
strings found in the heap blob that are referenced in the user code. The strings are kept in Unicode encoding.
Babel has different methods (algorithms) of encrypting strings: xor and hash. Each algorithm can be specified
in the command line by using the option –string. If the user does not specify the encryption method, Babel will
choose the hash algorithm if a Professional or Enterprise license is available otherwise it will chose the xor
algorithm. The xor algorithm is the simplest one and consists of xor-ed in lined string characters with a
random integer key. This method is not tamper proof.
The xor method encryption is shown in the following screenshots. The image on the left shows the original
code disassembly with a string referenced by the instantiation of the OpenFileDialog class, while the image on
the right shows the same code after xor string encryption.

Code Xor string encryption

The hash algorithm is based on hash tables addressed by integer keys. This algorithm performs compression
and encrypted of string data to reduce the overall file size of the obfuscated assembly. This algorithm also
ensures tamper-proof protection.

The following picture shows hash string encryption algorithm code disassembly:

Code Hash string encryption

Babel also supports custom string encryption. With custom string encryption the user must provide in the
target assembly two methods: one for encrypting strings named EncryptString, and one named DecryptString.
The prototype for these two methods is the same: they both take a string as parameter and returns its
encrypted or decrypted string value:

/// <summary>
/// Encrypt an user string.
/// </summary>
/// <param name="text">The user string to encrypt.</param>
/// <returns>The encrypted user string.</returns>
internal static string EncryptString(string text)
{
// Encrypt text string and return the encrypted string object.
return ...;
}
79

/// <summary>
/// Decrypt an encrypted user string.
/// </summary>
/// <param name="text">The encrypted string.</param>
/// <returns>The decrypted user string.</returns>
internal static string DecryptString(string text)
{
// Decrypt text string and return the decrypted string object.
return ...;
}

Babel will search for these two methods, and use them when encrypting strings. At the end of the string
encryption phase, Babel will remove the EncryptString methods because they’re not necessary at runtime.
Another way to specify custom string encryption methods is to add the attributes
EncryptStringMethodAttribute and DecryptStringMethodAttribute for encrypt and decrypt
methods respectively. When these two attributes are specified, the EncryptString and DecryptString methods
can have any user-defined name:

using Babel.Code;

[EncryptStringMethod]
internal static string MyEncryptString(string text)
{
}

[DecryptStringMethod]
internal static string MyDecryptString(string text)
{
}

These two attribute types are defined in the Babel.Code.dll assembly that must be referenced into the project
References in order to be used.

Follow the encryption algorithm compatibility table.

.NET
.NET Micro .NET Compact
Algorithm Framework Silverlight
Framework Framework
1.1 to 4.0
xor
hash
custom
80

Inline Values and Array Encryption


Constant values and arrays declared inline may contain sensitive information such as data encryption keys
that the user wants to hide to disassembler. Babel Obfuscator is able to encrypt constant values and arrays
inside a method, securing sensitive information and providing an extra protection layer.

The encryption of values and arrays is disabled by default and can be enabled by entering at the command
line the switch valueencryption:

babel.exe myapp.exe --valueencryption

The user can configure additional parameters passing additional key-value pairs to the valueencryption
command line option:

--valueencryption [<key>=<value>]

Admitted key value pairs:

Key Value Description


int32 On/Off Whether to encrypt Int32 values
int64 On/Off Whether to encrypt Int64 values
single On/Off Whether to encrypt Single values
double On/Off Whether to encrypt Double values
array On/Off Whether to encrypt Arrays

The following table shows a method using inline values and arrays before and after value encryption.

Before value encryption After value encryption

Babel is able to encrypt arrays of different types.


81

As for all other Babel obfuscator features, value encryption can be controlled by XML rules. It is possible to
encrypt values and arrays only on those methods that match XML rule filters.

The feature name to use is: “value encryption”:

<Rule name="reduce value encrypt1" feature="value encryption" exclude="true">


<Target>Methods</Target>
<Pattern>*</Pattern>
<HasAttribute
onEnclosingType="false">System.Runtime.CompilerServices.CompilerGeneratedAttribute,System.Dia
gnostics.DebuggerHiddenAttribute</HasAttribute>
<Description>Do not encrypt values in compiler generated methods.</Description>
</Rule>

Babel will show at the end of the obfuscation process, inline values and arrays encryption statistics:

Encrypt Values phase, elapsed time 00.276s


System.Int32: 2863
System.Int64: 0
System.Single: 37
System.Double: 38
System.Array: 5

Resource Encryption
Babel can compress and encrypt embedded resources to protect your resources and also to reduce the
overall assembly size. The encrypted resources are loaded at runtime when they are eventually needed.
The following pictures show an assembly with embedded resource before and after resource encryption.

Before resource encryption After resource encryption

Resource encryption can be used to hide WPF resources from being inspected by tools like .NET Reflector.
Please refer to the Technology Matrix to see where the resource encryption feature is available.
82

Dynamic Proxy Calls


With dynamic proxy calls it is possible to hide all the calls to external and internal methods, inside delegate
types dynamically built at runtime. To enable dynamic proxy calls generation, use the switch –proxy at the
Babel command line. When enabled, this option will configure Babel to create proxies for externals and
internals calls. It is also possible to pass an optional parameter to force the generation only for internal or
external calls:

babel myapp.exe –-proxy internal

Will generate proxies for only internal calls, while:

babel myapp.exe –-proxy all

Generates calls to internal and external methods.


The following table shows a method where internal and external calls were obfuscated using dynamic proxies.

Before dynamic proxy call obfuscation After dynamic proxy call obfuscation

The statistics at the end of the obfuscation process will show the number of delegate types generated and the
number of calls routed through proxies.

Dynamic Proxy Call phase, elapsed time 03.354s


Dynamic proxy call: external
Number of delegate types generated: 2334
Number of proxy calls: 15876

Dynamic proxies are built by means of dynamic methods so they can slow down the startup time of your
application. Presently dynamic proxies are supported only by .NET Framework 2.0/3.x/4.0 and Silverlight.
To see the platforms where Dynamic Proxy is available, please refers to the Technology Matrix.
83

Code Generation
Babel performs metadata optimizations during the obfuscation process. These optimizations aim to make the
code faster and reduce the assembly size making even the decompiled code harder to read. In this section we
will see how Babel can improve the generated code and how these optimizations affect the code readability.
84

Automatic Class Sealing


Classes that are not used as base classes in an inheritance chain can be sealed. When the JIT compiler sees
a call to a virtual method using a sealed type, it can produce more efficient code by calling the method non-
virtually.

This optimization can be enabled from the command line using the switch --seal and it affects all non-public
types defined into the target assembly.

babel.exe myapp.exe --seal

By defining an XML rule it is possible to selectively exclude the automatic class sealing for a subset of types
that match a regular expression:

<Rule name="seal classes" feature="optimizations" exclude="false">


<Pattern>Utilities.*</Pattern>
<Properties>
<ClassSealing>false</ClassSealing>
</Properties>
</Rule>

Note that we set the exclude attribute to false, otherwise all the optimizations included automatic class sealing
would have been disabled.

Removing of Unwanted Attributes


Most of the times, the compiler-generated code contains attributes that can be removed without affecting the
behavior of the application during execution. Babel can remove any attribute applied to a defined symbol
during the optimization process. For instance it is possible to remove attributes that are not useful to the
application itself like: CompilerGeneratedAttribute or DebuggerDisplayAttribute from the members defined into
the assembly. This will save bytes in the obfuscated target and will also avoid distinguishing between the
compiler generated and the user code.

This optimization can be enabled by entering at the command line the switch cleanattrs:

babel.exe myapp.exe --cleanattrs

The list of the attributes that will be removed is stored into the babel.exe.config file. To see the attributes that
are actually configured to be removed you can enter:

babel.exe –-help cleanattrs

cleanattrs (nocleanattrs, no-cleanattrs, ca)


usage: --[no]cleanattrs
Enable ([no]disable) removal of unwanted attributes (alias: --ca) (default: disabled)

Unwanted attributes:

[mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute
[mscorlib]System.Diagnostics.DebuggerDisplayAttribute
[mscorlib]System.Diagnostics.DebuggerBrowsableAttribute
[mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute
[mscorlib]System.Diagnostics.DebuggerHiddenAttribute
[mscorlib]System.Diagnostics.DebuggerStepThroughAttribute

This list is stored in the babel.exe.config configuration section at the element UnwantedAttributes. The
element is a string collection in which each item is given by the qualified attribute type name:
85

<setting name="CleanupUnwantedAttributes" serializeAs="String">


<value>True</value>
</setting>
<setting name="UnwantedAttributes" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>[mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute
</string>
<string>[mscorlib]System.Diagnostics.DebuggerDisplayAtrribute</string>
</ArrayOfString>
</value>
</setting>

An XML rule property is also available to finely configure attributes removal for all members matching a given
regular expression similar to the one described for automatic class sealing:

<Rule name="unwanted attributes" feature="optimizations" exclude="false">


<Pattern>Utilities.*</Pattern>
<Properties>
<UnwantedAttributes>false</UnwantedAttributes>
</Properties>
</Rule>

System.Enum Types Removal


Babel can remove, whenever possible, System.Enum types defined into the target assembly by replacing their
fields with the relative values. This optimization saves disk space and also makes the disassembled code
more difficult to understand due to the use of constants instead of field names.

To enable the removal of enumeration types, enter at the command line the option enumremoval:

babel.exe myapp.exe --enumremoval

The optimization feature provides the EnumRemoval Boolean property that can be used to selectively exclude
or include the enumeration types.

<Rule name="enum removal" feature="optimizations" exclude="false">


<Pattern>Utilities.*</Pattern>
<Properties>
<EnumRemoval>false</EnumRemoval>
</Properties>
</Rule>
86

Code Instrumentation
Code instrumentation allows injection of code into an assembly by hooking the entry and exit of any method or
property or the catch of any exception. This is typically used to intercept function calls to either monitor the
execution or perform custom exception management.
In order to hook the entry/exit points of a method, user must provide the methods to be called when the
execution path reach either the entry or exit of any method. It is also possible to intercept the occurrence of
any managed exception and forward the execution to custom methods to handle the occurrence of the error.
The practical uses of instrumentation are many. Because the code is instrumented at post-build, the
developer can flavor the application with enhanced logging functionalities, custom exception management or
code profiling, with little effort. It is even possible to implement a custom protection based on instrumented
code and let Babel to manage the injection of protection routines.
87

Activating Instrumentation
The command switches related to code instrumentation can be found under the Code Generation section at
Babel help menu. Basically there are three options available: addreference <assembly>, [no]instrument
[regex] and [no]emptymethods. The most important option is instrument [regex]; we will see the description of
the other commands later in this chapter. With this option, you can establish the set of methods that have to
be instrumented. The command works like msilencryption command and it accepts an optional regular
expression used to catch all the methods that are matching the regular expression given. Because this
command can be entered multiple times at the command line, it is possible to build a complex set of methods
coming from different types or namespaces. The command regular expression is optional and if omitted will
lead the search for methods to be instrumented to the rules defined in XML rules files. In case there are no
XML rules files and no regular expression specified, the set of method to instrument will be empty and no
methods will be instrumented.

Once the set of methods to instrument is established there is another fundamental thing that Babel needs to
know i.e. the stub methods. These methods are called when the entry and exit point of each method is
reached or whenever a managed exception is thrown.

Basically there are three stub methods that can be defined: the first is called when the entry point is reached
and it has the following signature:

public static void OnEntry(object instance, MethodBase method, params object[] args)
{
}

The object instance parameter contains the reference to the calling method object or null in case the method
is static. The MethodBase method parameter provides information about the instrumented method, while the
params object[] args will represent the method arguments object array.

The second stub is called when a method exit point is reached and it has the following signature:

public static void OnExit(object instance, MethodBase method)


{
}

Where instance and method parameters have the same meaning described in the OnEntry method.

The last stub is called whenever a managed exception is thrown inside a method end it has the following
signature:

public static bool OnException(object instance, MethodBase method, Exception e)


{
}

Note that the Exception e parameter will contains the instance of the exception caught. This will be null in
case the type of the catch clause has not been specified.

To let Babel know about these methods the user can decorate each method with the appropriate
System.Reflection.ObfuscationAttribute attribute using the Feature string constructor parameter to target the
specific method definition:

[Obfuscation(Feature = "instrumentation on entry method")]


public static void OnEntry(object instance, MethodBase method, params object[] args)

[Obfuscation(Feature = "instrumentation on exit method")]


public static void OnExit(object instance, MethodBase method)

[Obfuscation(Feature = "instrumentation on exception method")]


public static bool OnException(object instance, MethodBase method, Exception e)
88

The name given to the methods is not relevant; while the method signature (i.e. the number and order of
method parameter as well as its return type) should be respected to ensure that Babel recognizes the
methods as valid stub. Note that the presence of the OnEntry stub method is always required in conjunction
with one of the OnExit or OnException methods.

Wherever is not possible to use the System.Reflection.ObfuscationAttribute attribute to indicate the stubs
methods, XML rule files should be used. For example the following XML rule file can be used to declare the
three method stubs defined into the Tracer class:

<?xml version="1.0" encoding="utf-8" ?>


<Rules version="2.0">
<Rule name="entry" feature="instrumentation on entry method" exclude="false">
<Target>Methods</Target>
<Pattern>SimpleTracer.Tracer.OnEntry*</Pattern>
</Rule>
<Rule name="exit" feature="instrumentation on exit method" exclude="false">
<Target>Methods</Target>
<Pattern>SimpleTracer.Tracer.OnExit*</Pattern>
</Rule>
<Rule name="exception" feature="instrumentation on exception method" exclude="false">
<Target>Methods</Target>
<Pattern>SimpleTracer.Tracer.OnException*</Pattern>
</Rule>
</Rules>

Simple Tracing Walkthrough


This walkthrough give step-by-step instructions to build a simple tracing and logging component that will be
used by Babel to instrument an application. This makes it a good place to start learning about using Babel
code instrumentation. For this walkthrough we will use Visual Studio 2010.

Creating SimpleTrace Project


To create the SimpleTrace class library and Trace component

1. From the File menu, select New and then Project to open the New Project dialog. Select the Class
Library project template from the list of Visual C# project types, and enter SimpleTrace in the Name
box.
2. In Solution Explorer, right-click Class1.cs and select Rename from the shortcut menu.
3. Enter the new name Tracer.cs and press enter.
Visual Studio will display a message box asking to rename all references to the code element
Class1. Press Yes.
4. In Solution Explorer, double click Traces.cs to open the Tracer class definition into the Code
Editor.
5. Add the following using statement to the list of using statements at the top of the Code Editor for
Tracer.

using System.Reflection;

6. Apply the following attribute to the Tracer class:

[Obfuscation(Feature = "instrumentation", Exclude = true, ApplyToMembers = true)]


public class Tracer
{
}
89

7. Add the following code inside the Tracer class definition:

public static readonly Tracer Instance = new Tracer();

private Tracer()
{
}

private void OnMethodEntry(object instance, MethodBase method, params object[] args)


{
System.Diagnostics.Trace.WriteLine(String.Format("{0}::{1}",
method.DeclaringType.FullName, BuildMethodSignature(method, args)));

System.Diagnostics.Trace.Indent();
}

private bool OnMethodException(object instance, MethodBase method, Exception e)


{
// Note that the Exception e parameter can be null
// in case the catch type has not been specified
System.Diagnostics.Trace.TraceError("Method {0} throws an exception: {1}",
method.Name, e);

// true = Rethrow the exception


return true;
}

private void OnMethodExit(object instance, MethodBase method)


{
System.Diagnostics.Trace.Unindent();
}

private string BuildMethodSignature(MethodBase method, object[] args)


{
StringBuilder sb = new StringBuilder();
sb.Append(method.Name);
sb.Append('(');
ParameterInfo[] parameters = method.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
if (i > 0)
sb.Append(", ");

ParameterInfo paramInfo = parameters[i];


sb.Append(paramInfo.ParameterType.FullName);

try
{
if (i < args.Length)
{
object arg = args[i];
sb.AppendFormat("={0}", arg == null ? "null" : arg.ToString());
}
}
catch (Exception e)
{
System.Diagnostics.Trace.TraceError(e.ToString());
System.Diagnostics.Trace.TraceError(String.Format("Parameter {0}={1}", i,
paramInfo.ParameterType.FullName));
}
}
90

sb.Append(')');
return sb.ToString();
}

Adding stub methods and building the project


To add the stub OnEntry, OnException and OnExit methods

1. Locate the constructor for Tracer (private Tracer()), and add the following code after the method
closing bracket.

[Obfuscation(Feature = "instrumentation on entry method")]


public static void OnEntry(object instance, MethodBase method, params object[] args)
{
Tracer.Instance.OnMethodEntry(instance, method, args);
}

[Obfuscation(Feature = "instrumentation on exception method")]


public static bool OnException(object instance, MethodBase method, Exception e)
{
return Tracer.Instance.OnMethodException(instance, method, e);
}

[Obfuscation(Feature = "instrumentation on exit method")]


public static void OnExit(object instance, MethodBase method)
{
Tracer.Instance.OnMethodExit(instance, method);
}

2. Press Ctrl+Shift+B to build the project.

Creating an Obfuscation Test Project


To create a simple obfuscation test Console application

1. In Solution Explorer, right-click the Solution ‘SimpleTrace’ node and select Add an then New
Project from the shortcut menu.
2. Select the Console Application project template from the list of Visual C# project types, and enter
TraceClient in the Name box.
3. In Solution Explorer, double click Program.cs to open the Program class definition into the Code
Editor.
4. Add the following code inside the Program class after the Main() method definition:

private static long Factorial(long val)


{
return val <= 1 ? 1 : val * Factorial(val - 1);
}

5. Inside the Main() method definition add the following code:

for (int i = 5; i >= 0 ; i--)


{
Console.WriteLine("1000 / ({0}! - 1) = {1}", i, (1000 / (Factorial(i) - 1)));
}

6. In Solution Explorer right-click TraceClient project node and select Add then New Item from the
shortcut menu.
91

7. In the Add New Item dialog box, select Application Configuration File. Click Add to create the
App.config file.
8. Double click the App.config file to open in the Code Editor and insert the following XML fragment
inside the configuration element node:

<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracer.txt" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>

9. Press Ctrl+Shift+B to build the project.

Instrumenting the TestClient Application


To instrument the TestClient application using the trace functionalities implemented into SimpleTrace
component.

1. Copy the SimpleTrace.dll component to the TestClient build output folder (bin\Debug)
2. Open a DOS command window and set the current directory to the TestClient project output folder.
3. Enter the following Babel command line:

babel.exe @ TraceClient.exe --instrument .* --addreference SimpleTrace.dll

4. Copy the SimpleTrace.dll component and the TraceClient.exe.config configuration file to the
BabelOut folder.
5. Enter at the command line the following command:

BabelOut\TraceClient.exe

The TraceClient application should print the following:

1000 / (5! - 1) = 8
1000 / (4! - 1) = 43
1000 / (3! - 1) = 200
1000 / (2! - 1) = 1000

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.


at TraceClient.Program.Main(String[] args)

The instrumented TraceClient.exe should have generated the call trace ASCII file tracer.txt in the BabelOut
folder containing the following lines:

TraceClient.Program::Main(System.String[]=System.String[])
TraceClient.Program::Factorial(System.Int64=5)
TraceClient.Program::Factorial(System.Int64=4)
TraceClient.Program::Factorial(System.Int64=3)
TraceClient.Program::Factorial(System.Int64=2)
TraceClient.Program::Factorial(System.Int64=1)
TraceClient.Program::Factorial(System.Int64=4)
TraceClient.Program::Factorial(System.Int64=3)
TraceClient.Program::Factorial(System.Int64=2)
TraceClient.Program::Factorial(System.Int64=1)
TraceClient.Program::Factorial(System.Int64=3)
TraceClient.Program::Factorial(System.Int64=2)
TraceClient.Program::Factorial(System.Int64=1)
TraceClient.Program::Factorial(System.Int64=2)
92

TraceClient.Program::Factorial(System.Int64=1)
TraceClient.Program::Factorial(System.Int64=1)
TraceClient.exe Error: 0 : Method Main throws an exception:
System.DivideByZeroException: Attempted to divide by zero.
at TraceClient.Program.Main(String[] args)

Note that the ouput shows the trace of the exception thrown by the last call to the Factorial method.
93

Visual Studio
Integration
This section will describe how you can use Babel Obfuscator with common build tools like Visual Studio and
MSBuild. Visual Studio integration offers two different ways of obfuscating project assemblies. The first one
involves the editing of visual studio project files and it invokes Babel’s MSBuild task. The latter consists in
launching babel.exe from the post-build event Project Designer page.
94

Project File
To integrate Babel within Visual Studio (.*proj) file, open the project file and insert an Import element in the
Babel.Build.targets file. This file is located under the MSBuild folder inside the Babel installation directory
(usually C:\Program Files\Babel).

Follow the steps required to modify the Visual Studio (.*proj) file:

1) In Visual Studio Solution Explorer, select the project node, right-click, and from the context popup
menu choose the Unload Project command. When the project is unloaded, its icon changes to a
folder and the word '(unavailable)' appears next to it.
2) Right click the unloaded project, and from context popup menu choose Edit.
3) In the XML project file insert after the line:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

The following Import declaration:

<Import Project="<full path to Babel.Build.targets file>" />

For example:

<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />

4) Save and reload the project.

Rebuild the project and look at the Visual Studio Output panel to see Babel console output. The obfuscated
assembly is saved to .\BabelOut sub-folder relative to the target directory.

The Babel.Build.targets file contains the declaration of the Babel MSBuild task. This task starts babel.exe and
passes into the command line the option specified in the xml task definition. The default binding of Visual
Studio project properties with the Babel task options is specified in the Babel.Build.targets file. These
properties can be overridden in your (.*proj) file to customize the Babel task behavior. For instance, in
Babel.Build.targets the property UnicodeNormalization is set to true to enable Unicode normalization by
default:

<PropertyGroup>
<UnicodeNormalization>true</UnicodeNormalization>
</PropertyGroup>

If you want to disable Unicode normalization, insert into the “.*proj” file after the Babel import declaration:

<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />

The following lines:

<PropertyGroup>
<UnicodeNormalization>false</UnicodeNormalization>
</PropertyGroup>

Other properties are available to override. The complete set of available task properties is listed in the Babel
Task section.

How to Add an XML Rule File in Visual Studio Project


When Babel is configured to run as an MSBuild task in a Visual Studio Project (see
95

Visual Studio Integration), the simplest way to add an XML Rules file is to add to the Visual Studio Project an
XML file named BabelRules.xml. To Add an XML rules file, perform the following steps:

1) In Visual Studio Solution Explorer, right-click on the project node that you want to add the XML rules
file to.
2) Select from the popup menu Add -> New Item…
3) From the Add New Item dialog, select an XML file template and enter into the Name text field:
BabelRules.xml.
4) Fill the XML file with rule definitions.
5) Save and build the project.

Visual Studio Project File Samples

Enable Babel obfuscation on R elease build only


There is a property that can be used to switch Babel obfuscation ON or OFF in particular build configurations.
This is the EnableObfuscation property, and it is useful if you want to enable obfuscation in Release builds,
but disable in Debug builds:

<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />


<Choose>
<When Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PropertyGroup>
<EnableObfuscation>false</EnableObfuscation>
</PropertyGroup>
</When>
<When Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PropertyGroup>
<EnableObfuscation>true</EnableObfuscation>
<ILIterations>3</ILIterations>
<StringEncryption>true</StringEncryption>
</PropertyGroup>
</When>
</Choose>

When the Debug build is selected, the Babel task is disabled so that the babel.exe is not executed at the end
of the build process. The Babel task is enabled when Release build is active.

Obfuscate Silverlight XAP package


To obfuscate the silverlight XAP package directly, overrides the AfterBuild target and create the
BabelInputFile property inside MSBuild as follow:

<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />

<Target Name="AfterBuild">
<CreateProperty Value="@(_OutputPathItem->'%(FullPath)$(XapFilename)')">
<Output TaskParameter="Value" PropertyName="BabelInputFile"/>
</CreateProperty>
</Target>

The target AfterBuild will assign to BabelInputFile property the correct path to the XAP package that will be
obfuscated.

Obfuscating .NET Micro Framework applications


Assemblies compiled for .NET Micro frameworks needs to be further processed by .NET compilers before
being deployed to the target. This additional compilation step is performed to ensure the binary compatibility
96

with the target device. To obfuscate a .NET Micro Framework assembly the obfuscation process must be
carried out before this final step. This can be achieved by importing into your project file the
Babel.Build.targets MSBuild file as follows:

<Import Project="$(NetMfTargetsBaseDir)$(TargetFrameworkVersion)\CSharp.Targets" />


<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />

To enable enhanced obfuscation features configure the Babel MSBuild task adding the following section:

<Import Project="$(NetMfTargetsBaseDir)$(TargetFrameworkVersion)\CSharp.Targets" />


<Import Project="C:\Program Files\Babel\MSBuild\Babel.Build.targets" />
<Choose>
<When Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PropertyGroup>
<EnableObfuscation>true</EnableObfuscation>
<SuppressReflection>true</SuppressReflection>
</PropertyGroup>
</When>
<When Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PropertyGroup>
<EnableObfuscation>true</EnableObfuscation>
<SuppressReflection>true</SuppressReflection>
</PropertyGroup>
</When>
</Choose>

See what features are available to .NET Micro Framework from the Technology Matrix.

Post Build Event


If you don’t want to edit Visual Studio projects, you can always obfuscate your assemblies from within Visual
Studio by launching babel.exe in a post build event. Just open the Build Events page of the Project Designer
to specify the babel.exe post build command:

babel.exe "$(TargetDir)$(TargetFileName)" -v1 --keyfile "$(ProjectDir)StrongName.snk" --rules


"$(ProjectDir)babelRules.xml"

To successfully run the event command, babel.exe must be available in your system PATH. The command-
line syntax can include any build macro.
97

MSBuild Task
Babel comes with support for the MSBuild tool by means of a custom task that performs the Babel obfuscation
launching the babel.exe command with options read from task properties. The Babel MSBuild task is defined
in the assembly Babel.Build.dll located in the MSBuild folder under the program installation directory (usually:
C:\Program Files) and also under the system Global Assembly Cache.
98

The Babel Task


Babel task can be added to any MSBuild project by inserting the appropriate UsingTask element into the
MSBuild project xml file:

<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0,


Culture=neutral, PublicKeyToken=138d17b5bd621ab7" />

Consider the following very simple C# project made by one executable assembly that references one DLL
library. We use this sample to describe how to make an MSBuild project that uses the Babel task. The main
assembly HelloWorld.exe is a console application that makes a call to a static method Hello.ToConsole()
defined in the HelloLib.dll assembly:

Main.cs
using System;
using HelloLib;

namespace HelloApp
{
class Program
{
public static void Main(string[] args)
{
Hello.ToConsole();
}
}
}

HelloLib.cs
using System;

namespace HelloLib
{
public class Hello
{
public static void ToConsole()
{
Console.WriteLine("Hello");
}
}
}

First we need to create an MSBuild project file: Hello.proj to build the Main.cs and HelloLib.cs source files into
their respective assemblies and include the UsingTask element to reference the Babel task.

<?xml version="1.0" encoding="UTF-8"?>


<Project
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0,


Culture=neutral, PublicKeyToken=138d17b5bd621ab7"/>

</Project>

To tell MSBuild to compile the HelloLib.cs file into HelloLib.dll assembly, we define a Task that calls the C#
compiler (CSC) on HelloLib.cs and specify the file format library for the output file using the TargetType
attribute:
99

<?xml version="1.0" encoding="UTF-8"?>


<Project
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0,


Culture=neutral, PublicKeyToken=138d17b5bd621ab7"/>

<ItemGroup>
<CSLibFile Include="HelloLib.cs"/>
</ItemGroup>

<Target Name="HelloLib">
<Message Text="Building $(TargetFile)..."/>
<CSC Sources="@(CSLibFile)"
WarningLevel="$(WarningLevel)"
TargetType="library">
</CSC>
</Target>
</Project>

Now we need to define another Target that compiles the file Main.cs and builds the HelloWorld.exe
application using as reference the HelloLib.dll library:

<?xml version="1.0" encoding="UTF-8"?>


<Project DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0,


Culture=neutral, PublicKeyToken=138d17b5bd621ab7"/>

<PropertyGroup>
<AppName>HelloWorld</AppName>
<LibName>HelloLib</LibName>
</PropertyGroup>

<ItemGroup>
<CSLibFile Include="HelloLib.cs"/>
</ItemGroup>

<ItemGroup>
<CSFile Include="Main.cs"/>
</ItemGroup>

<Target Name="HelloLib">
<Message Text="Building $(LibName)..."/>
<CSC Sources="@(CSLibFile)"
WarningLevel="$(WarningLevel)"
TargetType="library">
</CSC>
</Target>

<Target Name="Build" DependsOnTargets="HelloLib">


<Message Text="Building $(Appname)..."/>
<CSC Sources="@(CSFile)"
References="$(LibName).dll"
WarningLevel="$(WarningLevel)"
OutputAssembly="$(AppName).exe">
</CSC>
</Target>
</Project>
100

Because the project file contains multiple targets we need to specify the DefaultTargets attribute into the
Project element so that MSBuild knows to execute the Build target first. Note that the Build target depends on
the HelloLib target because the referenced assembly needs to be available when the Main.cs file is compiled.
We can build the HelloWorld.exe application by entering into the command shell the command:

msbuild.exe Hello.proj

We now have the HelloWorld.exe application, but we did not use the Babel task yet. Suppose that we want to
obfuscate only the HelloWorld.exe assembly. This can be easily done by adding to the Build target the Babel
task declaration:

<Target Name="Build" DependsOnTargets="HelloLib">


<Message Text="Building $(Appname)..."/>
<CSC Sources="@(CSFile)"
References="$(LibName).dll"
WarningLevel="$(WarningLevel)"
OutputAssembly="$(AppName).exe">
</CSC>

<Babel InputFile="$(AppName).exe"/>

</Target>

The only task attribute that we need to specify is the InputFile attribute. This attribute is mandatory and is
equivalent to specifying the primary assembly source into the babel.exe command line. The task so defined
will start babel.exe to obfuscate the HelloWorld.exe primary assembly using the default options. The
obfuscated assembly will be saved into the BabelOut folder.

The Babel task is able to locate the babel.exe tool under the system “Program Files” folder when installed into
the standard Babel directory. If the Babel setup was performed to install the program under a directory with a
different name, the Babel task will not be able to find the babel.exe executable and the build process will
terminate with an error. In this scenario we need to specify the Babel installation directory as input to the
Babel task by using the attribute BabelDirectory:

<Babel BabelDirectory="C:\Program Files\Babel Obfuscator"


InputFile="$(AppName).exe"/>

You can add more attributes to customize the Babel behavior. For instance, if you want to save the
obfuscated assembly with a different name you can add the OutputFile attribute with the name of the
obfuscated executable:

<Babel InputFile="$(AppName).exe"
OutputFile="$(AppName)_babel.exe"/>

The obfuscated assembly will be saved in the same folder as the primary source with the name:
HelloWorld_babel.exe. You can also change the encryption string algorithm used when Babel encrypt strings
by specifying the StringEncryptionAlgorithm attribute:

<Babel InputFile="$(AppName).exe"
StringEncryptionAlgorithm="hash"
OutputFile="$(AppName)_babel.exe"/>

You can also instruct the Babel task to merge the referenced assembly HelloLib.dll into the primary assembly
by adding the MergeFiles attribute:

<Babel InputFile="$(AppName).exe"
MergeFiles="$(LibName).dll"
Internalize="true"
StringEncryptionAlgorithm="hash"
OutputFile="$(AppName)_babel.exe"/>
101

The Internalize attribute changes the visibility of Hello class so that it will be visible only to types defined
internally to the merged assembly, making the Hello class name available to be obfuscated. If you wanted to
merge multiple libraries into the primary assembly you need to specify the names of the libraries separated by
a semicolon:

MergeFiles="$(LibName1).dll;$(LibName2).dll"

Now suppose that you wanted to encrypt all the methods defined in the HelloLib.dll assembly. Usually to do
this you would need to define a rules XML file to target the msil encryption feature and pass to the babel.exe
command line the msilencrypt option. With a Babel task you can do the same by adding two attributes: the
first, RulesFiles, defines a list of XML rules files to use as input. The second, MsilEncryption, tells babel.exe to
run the MSIL encryption phase.

<Babel InputFile="$(AppName).exe"
MergeFiles="$(LibName).dll"
Internalize="true"
StringEncryptionAlgorithm="hash"
RulesFiles="babelRules.xml"
MsilEncryption="true"
OutputFile="$(AppName)_babel.exe"/>

The babelRules.xml file is defined as follow:

<?xml version="1.0" encoding="utf-8"?>


<Rules version="2.0">
<Rule name="encrypt" feature="msil encryption" exclude="false">
<Target>Methods</Target>
<Pattern>HelloLib.*</Pattern>
<Properties>
<Cache>true</Cache>
</Properties>
<Description>Encrypt HelloLib methods.</Description>
</Rule>
</Rules>

Babel MSBuild Project Files


Babel obfuscator is able to generate an MSBuild project file containing the necessary build instruction to
perform the obfuscation configured at the command line. This eases the setup of the obfuscation process and
also provides a handy way to generate the MSBuild Babel task element to insert inside a Visual Studio
project. For instance the following command line:

babel myapp.exe myapp.Core.dll myapp.Data.dll myapp.GUI.dll myapp.Resources.dll --out


myapp.exe -v2 --rules babelRules.xml --internalize --ildasm --noinvalid –msilencrypt .* --
makeproject .\myapp.blproj

Generates the myapp.blproj MSBuild project file:

<?xml version="1.0" encoding="utf-8"?>


<Project ToolsVersion="3.5" DefaultTargets="Obfuscate"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="Babel" AssemblyName="Babel.Build, Version=5.6.0.0, Culture=neutral,
PublicKeyToken=138d17b5bd621ab7" />
<PropertyGroup>
<BabelInputFile>myapp.exe</BabelInputFile>
<OverloadedRenaming>true</OverloadedRenaming>
<StringEncryption>true</StringEncryption>
<FlattenNamespaces>true</FlattenNamespaces>
<DeadCodeElimination>false</DeadCodeElimination>
<ILIterations>3</ILIterations>
102

<DynamicProxy>None</DynamicProxy>
<BabelOutputFile>myapp.exe</BabelOutputFile>
<SealClasses>false</SealClasses>
<ShowLogo>true</ShowLogo>
<MsilEncryption>.*</MsilEncryption>
<ShowStatistics>true</ShowStatistics>
<ObfuscateXaml>false</ObfuscateXaml>
<VerboseLevel>2</VerboseLevel>
<ObfuscateProperties>true</ObfuscateProperties>
<SuppressIldasm>false</SuppressIldasm>
<ObfuscateFields>true</ObfuscateFields>
<GenerateDebug>false</GenerateDebug>
<ObfuscateMethods>true</ObfuscateMethods>
<EnableObfuscationAgent>true</EnableObfuscationAgent>
<SuppressReflection>false</SuppressReflection>
<ControlFlowObfuscation>
true;token=false;underflow=false;goto=true;if=true;switch=true;case=true
</ControlFlowObfuscation>
<VirtualFunctions>true</VirtualFunctions>
<ObfuscateEvents>true</ObfuscateEvents>
<ObfuscateTypes>true</ObfuscateTypes>
<ResourceEncryption>false</ResourceEncryption>
<UnicodeNormalization>true</UnicodeNormalization>
</PropertyGroup>
<ItemGroup>
<MergeAssembly Include="myapp.Core.dll" />
<MergeAssembly Include="myapp.Data.dll" />
<MergeAssembly Include="myapp.Effects.dll" />
<MergeAssembly Include="myapp.Resources.dll" />
</ItemGroup>
<ItemGroup>
<RuleFile Include="babelRules.xml" />
</ItemGroup>
<Target Name="Obfuscate">
<Message Text="Obfuscating $(BabelInputFile)..." />
<Babel InputFile="$(BabelInputFile)" OutputFile="$(BabelOutputFile)" MergeAssemblies="@(MergeAssembly)"
RulesFiles="@(RuleFile)" ShowLogo="$(ShowLogo)" EnableObfuscationAgent="$(EnableObfuscationAgent)"
FlattenNamespaces="$(FlattenNamespaces)" UnicodeNormalization="$(UnicodeNormalization)"
ObfuscateTypes="$(ObfuscateTypes)" ObfuscateEvents="$(ObfuscateEvents)" ObfuscateMethods="$(ObfuscateMethods)"
ObfuscateProperties="$(ObfuscateProperties)" ObfuscateFields="$(ObfuscateFields)"
ObfuscateXaml="$(ObfuscateXaml)" VirtualFunctions="$(VirtualFunctions)"
OverloadedRenaming="$(OverloadedRenaming)" ControlFlowObfuscation="$(ControlFlowObfuscation)"
ILIterations="$(ILIterations)" StringEncryption="$(StringEncryption)" MsilEncryption="$(MsilEncryption)"
DynamicProxy="$(DynamicProxy)" ResourceEncryption="$(ResourceEncryption)" SuppressIldasm="$(SuppressIldasm)"
SuppressReflection="$(SuppressReflection)" SealClasses="$(SealClasses)"
DeadCodeElimination="$(DeadCodeElimination)" GenerateDebug="$(GenerateDebug)" VerboseLevel="$(VerboseLevel)"
ShowStatistics="$(ShowStatistics)" />
</Target>
</Project>

Once we have the project file, it is possible to perform the same obfuscation with msbuild.exe or babel.exe:

msbuild.exe myapp.blproj

babel.exe –-project myapp.blproj

MSBuild will start Babel passing the same command line switches used earlier.
103

Task Attributes
There are many attributes available to customize the obfuscation process under MSBuild. The following table
shows all the known Babel task attributes and the related properties defined in the Babel.Build.targets file.

Task Attribute Babel.Build.targets Type Description


BabelDirectory BabelDirectory String Full path to babel.exe tool
- EnableObfuscation Boolean Global switch to enable or
disable the obfuscation
process
ShowLogo ShowLogo Boolean Outputs Babel copyright
information
ShowStatistics ShowStatistics Boolean Whether you want Babel to
Miscellaneous

show obfuscation statistics


VerboseLevel VerboseLevel Int32 Console output verbosity
XapCompressionLevel XapCompressionLevel Int32 XAP package compression
level
EnableObfuscationAgent EnableObfuscationAgent Boolean Whether to enable agent
task processing
- BabelRulesFileName String BabelRules.xml
SatelliteAssemlies SatelliteAssemlies String List of assembly files to
process as satellite
assemblies
SearchDirectories SearchDirectories String List of directories where
Babel search to resolve
referenced assemblies
TakeFiles BabelTakeFiles String List of regular expressions
to match against deployed
XAP package assemblies
that should be obfuscated.
This property is equivalent
to the –take Babel
Miscellaneous

command line switch.


SkipFiles BabelSkipFiles String List of regular expressions
to match against deployed
XAP package assemblies
that should not be
obfuscated. This property is
equivalent to the –skip
Babel command line switch.
NoWarnings NoWarnings String List of warning message
codes to ignore
QuickRules QuickRules String List of quick rule definitions
MergeAssemblies MergeAssemblies String List of assembly files to
merge into the primary
Merge and Embed

assembly
Assemblies

Internalize MergeInternalize Boolean Whether merged types have


their visibility restricted to
the assembly
CopyAttributes MergeCopyAttributes Boolean Whether assembly-level
attributes of merged
assemblies are copied into
the target assembly
104

Task Attribute Babel.Build.targets Type Description


EmbedAssemblies EmbedAssemblies String List of assembly files to
embed into the primary
assembly

ObfuscateTypes ObfuscateTypes Boolean Whether to obfuscate the


names of types
ObfuscateEvents ObfuscateEvents Boolean Whether to obfuscate the
names of events
ObfuscateMethods ObfuscateMethods Boolean Whether to obfuscate the
names of methods
ObfuscateProperties ObfuscateProperties Boolean Whether to obfuscate the
names of properties
ObfuscateFields ObfuscateFields Boolean Whether to obfuscate the
names of fields
Renaming

ObfuscateXaml ObfuscateXaml Boolean/ Whether to obfuscate the


Key=Value symbols inside XAML/BAML
resources
VirtualFunctions VirtualFunctions Boolean Whether to enable virtual
member name obfuscation
OverloadedRenaming OverloadedRenaming Boolean Whether to overload method
names when possible
FlattenNamespaces FlattenNamespaces Boolean Whether namespace names
information should have
their types’ visibility
restricted to the assembly
UnicodeNormalization UnicodeNormalization Boolean/String Whether to obfuscate
member names using
Unicode symbols
ControlFlowObfuscation ControlFlowObfuscation Boolean Whether to enable MSIL
Key=Value control flow obfuscation
Control Flow
Obfuscation

ILIterations ILIterations Int32 Number of iterations used in


the control flow obfuscation
algorithm.

EmitInvalidOpcodes EmitInvalidOpcodes Boolean Whether to emit invalid op-


codes

MsilEncryption MsilEncryption Boolean/String Encrypt the IL of methods


that match a given regular
Encryption and Protection

expression
StringEncryption StringEncryption Boolean/String Whether to enable
encryption of user strings.
Optionally the encryption
string algorithm name can
be specified.
ValueEncryption ValueEncryption Boolean/ Whether to encrypt Inline
Key=Value Values and Arrays
ResourceEncryption ResourceEncryption Boolean Whether to encrypt
Resources
SuppressIldasm SuppressIldasm Boolean Whether to prevent ILDASM
from disassembling the
obfuscated target
105

Task Attribute Babel.Build.targets Type Description


SuppressReflection SuppressReflection Boolean Whether to prevent tools
using reflection from
displaying metadata.

AddReference AddReference String List of assembly files to


reference into the primary
assembly
Instrument Instrument Boolean/String Instrument methods that
Code Generation

match a given regular


expression
InstrumentEmptyMethods InstrumentEmptyMethods Boolean Whether to enable the
instrumentation of empty
methods
DeadCodeElimination DeadCodeElimination Boolean Whether to remove unused
methods from the target
assembly
SealClasses SealClasses Boolean Whether to seal classes
whenever is possible
CleanAttributes CleanAttributes Boolean Whether to cleanup
unwanted attributes
EnumRemoval EnumRemoval Boolean Whether to enable
System.Enum types
removal
ConstRemoval ConstRemoval Boolean Whether to enable constant
fields removal.
GenerateDebug GenerateDebug Boolean Whether to enable debug
symbols generation
OutputFile BabelOutputFile String Obfuscated target file path
PdbFile PdbFile String Debug symbols file path

GenerateLogFile GenerateLogFile Boolean Whether to generate


obfuscation log. The log file
Output Files

will be:
<target_assembly>.log
LogFile BabelLogFile String Obfuscation log file path
GenerateMapOutFile GenerateMapOutFile Boolean Whether to generate
obfuscation map file. The
map file path will be:
<target_assembly>.xml.map
MapOutFile BabelMapOutFile String File path of the output map
file
InputFile BabelInputFile String The path of the main
source assembly
(mandatory)
KeyFile KeyOriginatorFile String Path of the strong-name key
Input Files

file
KeyContainer KeyContainerName String Key container name
KeyPwd SigningCertPassword String Strong-name certificate
password
RulesFiles BabelRulesFiles String Semicolon-separated list of
rules file paths
MapInFiles BabelMapInFiles String List of XML map files to
process
Table 7 Babel task attributes
106

Customizing Project File Intellisense in Visual Studio


The MSBuild Babel task attributes are defined into the schema file Babel.Build.xsd located inside the
\Program Files\Babel\MSBuild installation folded. To integrate Babel task with Visual Studio Intellisense,
copy the file Babel.Build.xsd into Visual Studio install folder “\Program Files\Microsoft Visual Studio
10.0\Xml\Schemas\1033” and import it into the Microsoft.Build.xsd file as follow:

<!-- =================== IMPORT COMMON SCHEMA =========================== -->


<xs:include schemaLocation="MSBuild\Microsoft.Build.CommonTypes.xsd"/>
<xs:include schemaLocation="Babel.Build.xsd"/>

This will enable Intellisense or the Babel task inside the Visual Studio XML code editor.
107

Advanced Topics
In this section we’ll examine some advanced Babel usage topics like obfuscation of a Silverlight application
package, signing an assembly with Portable Information Exchange key, and successfully obfuscating
assemblies that target x64 Windows platforms. Following that is a description on how to store MSIL encrypted
method data into an external file instead of a managed resource, and use that file for loading encrypted code
at runtime. Another interesting technique is obfuscating the public members of an assembly that will be
referenced in the main application; that is explained in the Obfuscate Multiple Assembly section. Finally, we’ll
give you some hints on how to troubleshoot problems that sometimes occur during the obfuscation process.
108

Silverlight XAP Packages


Silverlight applications are deployed by means of XAP packages. A XAP package is a zip compressed file that
contains the application assemblies, resources and an application manifest AppManifest.xaml that defines the
assemblies to be deployed. With Babel you can obfuscate the assemblies contained in the XAP package
directly without working with individual assemblies outside the XAP package. Babel accepts as a primary
assembly source the XAP package itself and performs obfuscation of all the deployed assemblies in a XAP
package.

The deployed assemblies are those listed as <AssemblyPart> element in the AppManifest XML file as showed
in the following AppManifest.xaml file:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
EntryPointAssembly="SilverlightRichEdit" EntryPointType="SilverlightRichEdit.App"
RuntimeVersion="4.0.50401.0">
<Deployment.Parts>
<AssemblyPart x:Name="SilverlightRichEdit" Source="SilverlightRichEdit.dll" />
<AssemblyPart x:Name="RichEdit" Source="RichEdit.dll" />
<AssemblyPart x:Name="System.Xml.Serialization" Source="System.Xml.Serialization.dll" />
<AssemblyPart x:Name="System.Xml.Linq" Source="System.Xml.Linq.dll" />
<AssemblyPart x:Name="System.ComponentModel.DataAnnotations"
Source="System.ComponentModel.DataAnnotations.dll" />
</Deployment.Parts>
</Deployment>

It is common practice avoid obfuscating all Silverlight assemblies. To filter the assemblies that babel should
obfuscate you can use the take and skip command line options. These two options accept a regular
expression as an argument and those assembly names that will match the given expression will be taken or
skipped by the obfuscator.

babel.exe SilverlightRichEdit.xap –-take .*RichEdit –-skip System.*

Cross Referenced Members Obfuscation


To enable cross referenced members obfuscation and obfuscate all public members used between the
obfuscated assemblies you need to generate and pass map files and use an XML rule file to configure public
obfuscation (see Obfuscate Multiple Assemblies). This can be accomplished also when obfuscating XAP
packages. Just enter at the command line the switch mapout and Babel will generate for each obfuscated
assembly the corresponding map file to pass as an input to the next obfuscated assembly inside the XAP
package:

babel.exe SilverlightRichEdit.xap –-take .*RichEdit –-skip System.* --mapout


-–rules publicRules.xml

Babel is able to recognize the correct order in which the assemblies must be obfuscated and pass the correct
map files to the currently obfuscated assembly.

XAP Package Compression


Because the size of the XAP package affects the overall download time required to deliver the application to
the client, you can tweak the XAP package size increasing the compression level using the compress option:

babel.exe SilverlightRichEdit.xap –-take .*RichEdit –-skip System.* --mapout


-–compress 9

Admitted values are 0 (for no compression at all), to 9 (best compression). The size of the resulting package
depends on the content of the XAP package.
109

XAP Skip List


Silverlight XAP packages may contain assemblies that belong to the Silverlight library itself. These assemblies
should not be obfuscated and they must be specified at the command line after the skip option. This operation
may require the user to enter long command line sentences especially when there are many Silvelight
assemblies inside the XAP package. To avoid this repetitive task the user can add all the assemblies that are
often skipped in the obfuscation process inside the babel.exe.config configuration file using the XapSkipList
section as follow:

<setting name="XapSkipList" serializeAs="Xml">


<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>System.Windows.Controls</string>
<string>System.Windows.Data</string>
<string>System.Xml.Linq</string>
</ArrayOfString>
</value>
</setting>

Satellite Assemblies
Satellite assemblies are those generated by Visual Studio for projects that contain localized resources. These
localized assemblies contain only resources—no code. Babel can handle and automatically obfuscate satellite
DLLs that are part of an obfuscated executable. You don’t need to specify them on the command line as
inputs. Babel will search for assemblies’ culture-specific resources located in application directories named
after their localized culture names. For example, the application directory “Math” that contains Calculator.exe,
should contains a directory “it” which contains the satellite assembly localized for the Italian culture named
Calculator.resources.dll. Babel will rebuild the localized resource directories tree in the output folder.

Strong Name Assembly Signing Using PFX Key


Babel supports assembly re-sign with strong name key and PFX (Portable Information Exchange) file formats.
Also, the key container can be used to re-sign an obfuscated assembly. The re-signing is performed at the
end of the obfuscation process after the Emit phase. The command-line options that control the re-sign
process are: --keyfile, --keyname, and --keypwd. The keyfile option is used to set the key-pair file path. Babel
recognizes whether the key pair is a strong name key (.snk) or a Portable Information Exchange (.pfx) from
the file extension. The .snk format does not require any other information, whereas .pfx files need to be
unlocked by a password that should be specified using the --keypwd command-line option. If this option is not
specified in the command line, Babel will prompt the user to enter the proper password during the Emit phase.

Obfuscating x64 Assemblies


Depending on the target platform, the Visual Studio compiler emits the desired CPU architecture into the PE
header. Users of Visual Studio can set the target platform in the build project’s property page. The default
platform is “Any CPU” which indicates that the compiled assembly can run on any version of Windows. When
a managed executable is loaded, Windows examines the PE header to determine whether the application
requires 32-bit or 64-bit CPU architecture to ensure that it matches the computer’s CPU type. Windows
ensures the compatibility of 32-bit applications on 64-bit CPUs with a technology called WoW64 (Windows on
Windows64) that emulates 32-bit instruction sets on a 64-bit CPU, albeit with performance loss. When the
application architecture is known, Windows loads the framework execution engine Just-In-Time compiler (JIT)
specific to the executable target platform (x86, x64, Itanium). On x64 operating systems, the MSIL code of
assemblies targeting "Any CPU” platform is validated by the .NET Framework runtime before execution.
110

To protect an assembly from being disassembled by tools like .NET Reflector, Babel can inserts into any
MSIL method invalid byte codes that do not correspond to any MSIL op-code instruction (--invalidopcodes).
The resulting assembly is no longer IL verifiable and Windows can execute it only on a WoW64 subsystem.
Suppose that the obfuscated assembly is a DLL referenced by an executable that runs in full 64-bit
environment. When the runtime tries to load the DLL obfuscated with invalid op-codes, it checks the CPU JIT
requirements, and because they do not match, it throws an InvalidProgramException exception. The only way
to generate obfuscated DLLs or executables fully compatible with x64 is to disable the injection of invalid op-
codes during obfuscation.

Customize MSIL Encryption


With MSIL encryption the method code is hidden in a .NET Framework DynamicMethod object compiled at
runtime with encrypted code stored in a managed resource. The original method is reduced to a call to the
compiler engine stub. The DynamicMethod objects compiled with encrypted MSIL code are executed and
then discarded. Moreover, once compiled, they cannot be modified. This makes the reverse engineering of
encrypted methods very difficult. Commonly, the encrypted code is embedded into the assembly resources,
but Babel can also store the encrypted MSIL code in standard files that can be loaded at runtime by the
dynamic method compiler, that is embedded into the obfuscated assembly. This means that encrypted
methods are stripped out from the assembly and serialized into an external file. The obfuscated assembly
contains only calls to the compiler stub and there is no way to get the original method code without the
encrypted file. Those files can be used to implement a custom licensing method or even stored in a database
or secure store, and retrieved by the application when required.

To configure the generation of encrypted files, Babel needs to know the encrypted source name and the
method that should be called to retrieve the encrypted data. The former comes from XML rules files; the latter
from custom attributes. We have already seen in the MSIL Encryption section the XML properties available for
the “msil encryption” feature: Cache, MinInstructionCount, MaxInstructionCount and Source. Source contains
a string value that is the name of the encrypted data source associated with all the methods encrypted by the
rule. Consider the following XML rule:

<Rule name="Rgb" feature="msil encryption" exclude="false">


<Target>Methods</Target>
<Pattern>Utilities.Rgb::*</Pattern>
<Properties>
<Cache>true</Cache>
<Source>rgb</Source>
<MinInstructionCount>5</MinInstructionCount>
</Properties>
<Description>Encrypt methods of Rgb class.</Description>
</Rule>

This rule tells Babel to encrypt all the Rgb class methods that contain at least five MSIL instructions and to
assign the source name rgb to the encrypted data. Babel will generate in the output folder a file named rgb.eil
(where .eil stand for Encrypted IL) that contains the encrypted code that will be used by the dynamic method
compiler at runtime to generate the Rgb class methods.

Once you have the encrypted data files you need to tell Babel the method that will be used to retrieve the
encrypted stream at runtime. This can be done by using the custom attribute
System.Reflection.ObfuscationAttribute on an internal static method that takes the source name string as a
parameter and returns the encrypted MSIL System.IO.Stream object. The
System.Reflection.ObfuscationAttribute must specify the constructor-named parameter Feature as "msil
encryption get stream".

/// <summary>
/// Given the MSIL source name, returns the encrypted code stream.
/// </summary>
/// <param name="source">The name that identifies the source
/// stream.</param>
111

/// <returns>Encrypted MSIL source stream.</returns>


[Obfuscation(Feature="msil encryption get stream")]
internal static Stream GetSourceStream(string source)
{
}

At runtime, when an encrypted method of the Rgb class is called, the dynamic method compiler recognizes
that the encrypted method data is associated with an external source instead of the assembly-embedded
resource, and it will make a call to the method GetSourceStream with source argument equal to “rgb” to
retrieve the encrypted Stream object.
112

Obfuscate Multiple Assemblies


The obfuscation process itself can only rename the internally visible assembly symbols, leaving the public
members untouched. Otherwise the runtime execution of assemblies that consume the obfuscated types will
be compromised. Babel can obfuscate public members in multiple assemblies, fixing the name of obfuscated
symbols referenced in each assembly. Multiple-assembly obfuscation is made possible by means of map files.
Map files are XML files produced as output from the obfuscation process, and contain all the associations
between original and obfuscated symbol names. When using map files, it is possible to recover the original
symbol names from the obfuscated ones. Map files must not be deployed with the obfuscated application
under any circumstances. Keep them private.

Consider the following example of a managed application (Calculator.exe) that references two assembly
libraries: Algorithms.dll and Math.dll. Suppose that Algoritms.dll references Math.dll also. The reference graph
is represented as follows:

Calculator.exe

Algorithms.dll Math.dll

The two referenced assemblies: Algorithms.dll and Math.dll are general-purpose assemblies, used in several
other projects. We want to obfuscate the entire project without merging the referenced libraries, as they are
used by other applications as well and not just Calculator.exe. We want to keep the deployed package size as
small as possible, and exclusion of referenced assemblies will assist with that. Algorithms and Math
assemblies contain many public classes, so to effectively obfuscate the whole project we’d like to mangle
public members as well. Babel can address this issue by generating an obfuscation map file for each
referenced assembly that will have its public member obfuscated and use those map files when obfuscating
the main application assembly or every other assembly with references back to public obfuscated assemblies.

To set up the obfuscation process, first we need to tell Babel to obfuscate all public symbols of Math.dll and
Algorithms.dll assemblies. This can be done by inserting into the source code the following assembly-level
custom attribute declaration:

[assembly: System.Reflection.ObfuscateAssembly(true)]

This attribute provides a way to configure Babel to obfuscate public symbols without using external
configuration files. Setting the Boolean constructor parameter to true specifies that the assembly is private so
that public member names can be safely obfuscated. If you don’t want to change the source code you may
even create an XML rules file that forces the obfuscation of public member names:
113

<?xml version="1.0" encoding="utf-8"?>


<!--
publicRules.xml
-->
<Rules version="2.0">
<Rule name="Obfuscate public" exclude="false">
<Access>Public</Access>
<Pattern isRegEx="false">*</Pattern>
<Description>Obfuscate all public symbols.</Description>
</Rule>
</Rules>

Once we configure obfuscation of public symbols we are ready to start babel.exe, including in the command
line the option --mapout whenever we need to produce an output map file, and --mapin for each assembly that
has a reference to a previously obfuscated assembly. We need to start from the assemblies that have no
references to other obfuscated one. Returning to our Calculator example we can enter into a DOS shell the
following commands:

babel.exe Math.dll --rules publicRules.xml –-mapout

babel.exe Algorithms.dll --rules publicRules.xml –-mapout


--mapin Math.dll.map.xml

babel.exe Calculator.exe -–mapin Math.dll.map.xml --mapin Algorithms.dll.map.xml

Using this obfuscation feature it is possible to achieve a high level of renamed symbols, comparable to the
level obtained by merging referenced assemblies.
114

Troubleshooting a Broken Application


Every effort has been made to avoid runtime problems caused by obfuscation. But occasionally obfuscation
can break an application, or cause it to function in an unexpected manner. In this situation there are several
things that can be done. If you run a full obfuscation that involved renaming, string encryption, control flow
obfuscation, MSIL encryption and so on, try to lower the obfuscation level by running Babel with fewer tasks to
perform.

For instance, consider disabling only string encryption, and then check whether the obfuscated application is
fixed. If not, disable another phase like MSIL encryption, and then check again. If the problem persists, you
can disable the remaining options one by one. For example, to disable type obfuscation, enter in the
command line the option –notypes or its short form –not. If this fixes the application you will know that the
problem is with type renaming. Of course you can go on and disable all the other renaming options: -notmf
command will disable the renaming of types, methods and fields, leaving only events and properties
obfuscation. When you find the cause of the problem, you can refine your search by running the peverify.exe
tool on the obfuscated target. The hints that come from peverify should be enough to spot the cause of the
error and give you the necessary information to make a custom XML rule to avoid the obfuscation of the faulty
symbol.

There is another possibility of course: you found a bug in Babel. In this case, contact email support:

support@babelfor.net

Send all the useful information you can, such as:

 Operating system you are running on and processor architecture (x86 or x64)
 Babel command line used
 Babel log output (use the --logfile command line option)
 Peverify.exe output
 Steps required to reproduce the issue

The more information you send, the more likely it will be that we can reproduce and fix the problem. If
possible, you should also send the faulty assembly or, if this is not possible, a sample Visual Studio project
that reproduces the same issue. This last item is not always possible, but it would help us tremendously in
solving the problem.
115

Obfuscation Tips
This paragraph will give you a list of useful tips to protect better your application using Babel Obfuscator.

1. Consider to declare as many types as possible internal (VB Friend): Public types and methods
that are externally visible will not be renamed because they will be potentially used by other
assemblies. Internal (or Friends for VB) declared types are accessible from within the assembly and
are not visible to external assemblies so they can be safely obfuscated.

2. Enable always the Agent: The Agent can help you to avoid common obfuscation problems that
sometimes cause the obfuscated application to crash. It’s also useful to look at the output produced
by the Agent when you need to fine tune your XML rule files.

3. Use hash algorithm when encrypting strings: This will encrypt your strings binding the encrypted
data to strong name signature.

4. Enable dead code removal: At least this will spotlight unused method and give you some hint to
refactoring your code.

5. Do not MSIL encrypt too many methods: MSIL encryption is a powerful protection feature, but it
can slow down significantly the obfuscated application. Encrypt only those methods that run a limited
number of times and contains code that you want to secure.

6. Encrypt resource when necessary: resource encryption can hide all the embedded resource into
your assembly but it comes at a cost of decryption during execution. This will increase the time
needed by your application to access resources the first time.

7. Consider the environment your application is targeting: If your application is targeting x64
platform, don’t use invalid op-codes option because it will cause your application to run on WOW64.

8. Sign with strong name your assemblies: Babel bind encrypted data to assembly strong name and
insert custom code to detect data tampering.

9. Run peverify.exe /MD on the obfuscated assembly: This tool can tell you if the metadata of your
obfuscated application is verifiable.

10. Check the Babel command line output: The Babel output can give you a lot of information about
the obfuscation process and display warnings that should be always reviewed.

11. Test your obfuscated application: Obfuscation might break your code. To avoid any unexpected
behavior at runtime perform all the necessary tests on the obfuscated assemblies.
116

Appendix A
Warning Codes
The following table shows the list of warning codes and messages.
The codes can be used with command line option --nowarn.

Code Message
CF0001 Unknown invalid op-code mode: '{0}'.
EI0001 Missing key information, the target assembly strong name was removed.
EI0002 Cannot re-sign assembly. {0} does not represent a strongly named assembly.
EM0001 Methods that return pointers are not supported. {0}
EM0002 Methods with pointer parameters are not supported. {0}
EM0003 Methods with ref or out parameters are not supported. {0}
EM0004 Generic instance method inline tokens are not supported. {0}
EM0005 Inline metadata tokens are not supported. {0}
EM0006 Bad inline token type.
EM0007 Unknown metadata signature calling convention.
EM0008 Generic open types are not supported. {0}
EM0009 Generic parameter types are not supported. {0}
EM0010 Type not supported. {0}
MG0001 Found type name {0} defined into merged assembly {1} that already exists into the target
assembly. The defined type into the merged assembly will be renamed.
MG0002 Referenced assembly '{0}' has a reference to the merged assembly '{1}'.
MG0003 Resource data '{0}' into {1} has already been added.
MG0004 {0} (Could not resolve… generic warning message)
OB0001 Missing key information, the resource assembly '{0}' strong name was removed.
OB0002 The {0} named '{1}' defined into referenced assembly {2} should not be obfuscated.
OB0003 The property named '{0}' defined into referenced assembly {1} should not be obfuscated.
OB0004 The Unicode character set provided is not valid to rename {0} symbols{1}. The ASCII character
set will be used instead.
PR0001 Target already processed by Babel; some problems may occur at runtime or during obfuscation.
PR0002 {0} warning: missing {1} string method.
PR0003 Suppressing MSIL disassembler option is not supported on .NET Framework {0} assemblies.
PR0004 Suppress MSIL disassembler (ildasm.exe) option is not supported.
PR0005 Duplicate encrypt string method found {0}.
PR0006 Duplicate decrypt string method found {0}.
PR0007 String algorithm '{0}' is not supported on .NET Micro Framework assemblies. Algorithm '{1}' will
be used instead.
PR0008 Emit invalid op-codes option is not supported on {0} assemblies.
PR0009 The reference "{0}" has a higher version '{1}' than the version '{2}' in the current target.
PR0010 The assembly "{0}" is already present in the list of references.
PR0011 Dynamic proxy call option is not supported on {0} assemblies.
PR0012 Resource encryption is not supported on {0} assemblies.
PR0013 MSIL encryption is not supported on {0} assemblies.
PR0014 Assembly embedding is not supported on {0} assemblies.
RU0001 Rule '{0}' has an unknown property name '{1}'.
RU0002 Rules file unknown node {0} at line {1}, position {2}, node {3} '{4}'.
RU0003 Rules file unknown attribute at line {0}, position {1}, attribute {2}='{3}'.
RU0004 Unknown feature '{0}'.
W00001 Could not find debug symbols for {0}
W00002 Cannot parse {0} resource stream '{1}': {2}.
W00003 {0} resource stream '{1}'. Cannot resolve property '{2}' duplicate members found: {3}
W00004 Obfuscation Agent is disabled.
117

W00005 Debug symbols not loaded: {0}.


W00006 The member name '{0}' defined by the assembly '{1}' has been renamed according to the
information contained inside the XML map file. Please remove this member from the '{2}'
resource.
118

Unicode Character Ranges


0020 — 007F Basic Latin 2150 — 218F Number Forms
00A0 — 00FF Latin-1 Supplement 2190 — 21FF Arrows
0100 — 017F Latin Extended-A 2200 — 22FF Mathematical Operators
0180 — 024F Latin Extended-B 2300 — 23FF Miscellaneous Technical
0250 — 02AF IPA Extensions 2400 — 243F Control Pictures
02B0 — 02FF Spacing Modifier Letters 2440 — 245F Optical Character Recognition
0300 — 036F Combining Diacritical Marks 2460 — 24FF Enclosed Alphanumeric
0370 — 03FF Greek and Coptic 2500 — 257F Box Drawing
0400 — 04FF Cyrillic 2580 — 259F Block Elements
0500 — 052F Cyrillic Supplementary 25A0 — 25FF Geometric Shapes
0530 — 058F Armenian 2600 — 26FF Miscellaneous Symbols
0590 — 05FF Hebrew 2700 — 27BF Dingbats
0600 — 06FF Arabic 27C0 — 27EF Miscellaneous Mathematical Symbols-A
0700 — 074F Syriac 27F0 — 27FF Supplemental Arrows-A
0780 — 07BF Thaana 2800 — 28FF Braille Patterns
0900 — 097F Devanagari 2900 — 297F Supplemental Arrows-B
0980 — 09FF Bengali 2980 — 29FF Miscellaneous Mathematical Symbols-B
0A00 — 0A7F Gurmukhi 2A00 — 2AFF Supplemental Mathematical Operators
0A80 — 0AFF Gujarati 2B00 — 2BFF Miscellaneous Symbols and Arrows
0B00 — 0B7F Oriya 2E80 — 2EFF CJK Radicals Supplement
0B80 — 0BFF Tamil 2F00 — 2FDF Kangxi Radicals
0C00 — 0C7F Telugu 2FF0 — 2FFF Ideographic Description Characters
0C80 — 0CFF Kannada 3000 — 303F CJK Symbols and Punctuation
0D00 — 0D7F Malayalam 3040 — 309F Hiragana
0D80 — 0DFF Sinhala 30A0 — 30FF Katakana
0E00 — 0E7F Thai 3100 — 312F Bopomofo
0E80 — 0EFF Lao 3130 — 318F Hangul Compatibility Jamo
0F00 — 0FFF Tibetan 3190 — 319F Kanbun
1000 — 109F Myanmar 31A0 — 31BF Bopomofo Extended
10A0 — 10FF Georgian 31F0 — 31FF Katakana Phonetic Extensions
1100 — 11FF Hangul Jamo 3200 — 32FF Enclosed CJK Letters and Months
1200 — 137F Ethiopic 3300 — 33FF CJK Compatibility
13A0 — 13FF Cherokee 3400 — 4DBF CJK Unified Ideographs Extension A
1400 — 167F Unified Canadian Aboriginal 4DC0 — 4DFF Yijing Hexagram Symbols
1680 — 169F Ogham 4E00 — 9FFF CJK Unified Ideographs
16A0 — 16FF Runic A000 — A48F Yi Syllables
1700 — 171F Tagalog A490 — A4CF Yi Radicals
1720 — 173F Hanunoo AC00 — D7AF Hangul Syllables
1740 — 175F Buhid D800 — DB7F High Surrogates
1760 — 177F Tagbanwa DB80 — DBFF High Private Use Surrogates
1780 — 17FF Khmer DC00 — DFFF Low Surrogates
1800 — 18AF Mongolian E000 — F8FF Private Use Area
1900 — 194F Limbu F900 — FAFF CJK Compatibility Ideographs
1950 — 197F Tai Le FB00 — FB4F Alphabetic Presentation Forms
19E0 — 19FF Khmer Symbols FB50 — FDFF Arabic Presentation Forms-A
1D00 — 1D7F Phonetic Extensions FE00 — FE0F Variation Selectors
1E00 — 1EFF Latin Extended Additional FE20 — FE2F Combining Half Marks
1F00 — 1FFF Greek Extended FE30 — FE4F CJK Compatibility Forms
2000 — 206F General Punctuation FE50 — FE6F Small Form Variants
2070 — 209F Superscripts and Subscripts FE70 — FEFF Arabic Presentation Forms-B
20A0 — 20CF Currency Symbols FF00 — FFEF Halfwidth and Fullwidth Forms
20D0 — 20FF Combining Diacritical Marks FFF0 — FFFF Specials
2100 — 214F Letterlike Symbols
119

Index
. I
.NET Reflector, 11, 15, 40, 72, 73, 81, 110 ILDASM, 11, 15, 16, 41, 72, 73
ILMerge, 37
Input Files, 43
A Intellisense, 106
Invalid Op-Codes, 72
Activating Instrumentation, 87
Advanced Topics, 107
Any CPU, 109
L
Assembly Merge, 37
assembly re-sign, 109 License File, 22
automated build, 11, 24
Automatic Class Sealing, 84
M
B MaxInstructionCount, 76
MinInstructionCount, 76
BabelDirectory, 100 MSBuild, 97
MSIL Encryption, 11, 15, 17, 19, 23, 40, 75

C
O
Cache, 76
Code Instrumentation, 86 ObfuscateAssemblyAttribute, 54
Configuration File, 45 Obfuscation Agent, 48
Control Flow Obfuscation, 15, 17, 19, 23, 39, 47 ObfuscationAttribute, 54, 75, 110
custom string encryption, 78 Optimizations, 83
Output Files, 43
Overloaded Renaming, 17, 19, 23, 64
D
DecryptString, 78
P
Dynamic Proxy Calls, 82
DynamicMethod, 75, 76, 110 peverify.exe, 57, 114
PFX, 109
Phases, 47
E Portable Information Exchange, 109
private assembly, 54
Embed Assemblies, 59
EnableObfuscation, 95
EncrypString, 78
Q
Enhanced Control Flow Obfuscation, 71
extended help, 34 quick rule definition, 37

F R
Feature Matrix, 17 Renaming, 38, 61
Features, 14 Resource encryption, 81
reverse engineer, 11
Rules File, 50
H
hash, 78
120

S Unwanted Attributes, 84

Satellite Assemblies, 109 V


serializable types, 49
Setup, 26 Visual Studio integration, 93
SimpleTrace Project, 88
Source property, 110
String Encryption, 15, 17, 19, 23, 78 W
Strong Named Assemblies, 109
Warning Codes, 116
T Windows on Windows64, 109

Tracing Walkthrough, 88 X

U x64 bit, 26, 73


XAML and BAML Obfuscation, 65
XapSkipList, 109
Unicode Character Ranges, 118 xor, 78

You might also like