1

Babel Obfuscator User’s Guide

Version 8.9.0.0

2

Babel Obfuscator User’s Guide Manual Version 8.9.0.0 http://www.babelfor.net/

babelfor.NET Copyright © 2011-2016 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 .................................................................................................................................. 11 Introduction ............................................................................................................................................................ 12 Obfuscation at a Glance ................................................................................................................................................. 12 Benefits of Babel Obfuscator.......................................................................................................................................... 12 Software Requirements.................................................................................................................................................. 13 What’s New .................................................................................................................................................................... 14 Babel Obfuscator Release Notes .................................................................................................................................... 14 Assembly version 8.9.0.0, File version 8.9.0.0 ........................................................................................................... 14 Babel Features ......................................................................................................................................................... 15 Product Features ............................................................................................................................................................ 16 General Features ........................................................................................................................................................ 16 Obfuscation ................................................................................................................................................................ 16 Code Protection ......................................................................................................................................................... 16 Code Instrumentation and Optimization ................................................................................................................... 16 Deployment ............................................................................................................................................................... 17 Feature Matrix ................................................................................................................................................................ 18 Technology Matrix .......................................................................................................................................................... 20 Licensing ......................................................................................................................................................................... 22 Single user licenses .................................................................................................................................................... 22 Multi user license ....................................................................................................................................................... 22 Standard Licensing ..................................................................................................................................................... 22 Professional Licensing ................................................................................................................................................ 23 Enterprise/Company Licensing .................................................................................................................................. 23 Standard, Professional, Enterprise and Company Additional Benefits ...................................................................... 24 Licensing FAQ ................................................................................................................................................................. 24 License File ..................................................................................................................................................................... 24 Babel Obfuscator Version History .................................................................................................................................. 26 Latest Babel Obfuscator Commercial Version ................................................................................................................ 26 The Free Babel Obfuscator Version 2.0.0.1 .................................................................................................................... 26

5 Overview ........................................................................................................................................................................ 27 Starting Using Babel Obfuscator............................................................................................................................... 28 Setup .............................................................................................................................................................................. 29 MAC OSX Setup .............................................................................................................................................................. 30 Babel Obfuscator User Interface .................................................................................................................................... 31 Creating a New Solution File ...................................................................................................................................... 32 Changing Obfuscation Settings .................................................................................................................................. 34 Code Generation Options .......................................................................................................................................... 34 Setting the Output and Building the Project .............................................................................................................. 34 Examine the Obfuscated Assemblies ......................................................................................................................... 36 Deobfuscating Stack Trace ......................................................................................................................................... 37 Launching Babel from Command Line............................................................................................................................ 39 Miscellaneous ................................................................................................................................................................. 39 --help [option] (?) ....................................................................................................................................................... 39 --[no]logo

(enabled) ............................................................................................................................................. 40

--license ...................................................................................................................................................................... 40 --verbose (v) ........................................................................................................................................................ 40 --noconfig (@)

(disabled) ........................................................................................................................................ 40

--nowarn .................................................................................................................................................. 40 --[no]warnaserror [warn list] ..................................................................................................................................... 41 --[no]statistics

(enabled) ........................................................................................................................................ 41

--[no]agent (a)

(enabled) ........................................................................................................................................ 41

--[no]satellite [assembly] ........................................................................................................................................... 41 --addsearch .................................................................................................................................................... 41 --take ............................................................................................................................................................ 41 --skip ............................................................................................................................................................. 41 --compress

(6) .................................................................................................................................................. 41

--quickrule ....................................................................................................................................................... 42 --[no]removekey ........................................................................................................................................................ 42 --dbghelpdlldir ............................................................................................................................................... 42 --trace ........................................................................................................................................................... 42 --randomseed ................................................................................................................................................ 43 Plugins ............................................................................................................................................................................ 43 --plugin ............................................................................................................................................................. 43 --argument ............................................................................................................................................ 43 Merge and Embed Assemblies ....................................................................................................................................... 43

6 (disabled) .................................................................................................................................... 43

--[no]internalize

--[no]copyattrs [regex]

(enabled) ........................................................................................................................... 43

--embed .................................................................................................................................................. 43 Renaming........................................................................................................................................................................ 43 --[no]types (t)

(enabled) ......................................................................................................................................... 43

--[no]events (e)

(enabled)....................................................................................................................................... 44

--[no]methods (m)

(enabled) .................................................................................................................................. 44

--[no]parameters (r)

(enabled) ............................................................................................................................... 44

--[no]properties (p)

(enabled) ................................................................................................................................ 44

--[no]fields (f)

(enabled) ......................................................................................................................................... 44

--[no]xaml (x)

(disabled) ......................................................................................................................................... 44

--[no]virtual

(enabled) ............................................................................................................................................ 44

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

(disabled) .................................................................................................................................... 44 (enabled) ........................................................................................................................................ 44

--[no]unicode [char set] --namelength

(enabled) ......................................................................................................................... 44

(1) .............................................................................................................................................. 44

--nameprefix [prefix] .................................................................................................................................................. 45 --[no]xmldoc [file|regex]

(enabled) ........................................................................................................................ 45

Control Flow Obfuscation ............................................................................................................................................... 45 --[no]controlflow

(enabled) .................................................................................................................................... 45

--iliterations ......................................................................................................................................................... 46 --[no]invalidopcodes [mode]

(disabled) ................................................................................................................. 46

Encryption and Protection.............................................................................................................................................. 46 --[no]msilencryption [regex]

(disabled) .................................................................................................................. 46

--[no]stringencryption [name]

(enabled)................................................................................................................ 46

--[no]valueencryption [key=value] --[no]ildasm

(disabled) ........................................................................................................ 47

(enabled) ............................................................................................................................................ 47

--[no]reflection

(enabled) ....................................................................................................................................... 47

--[no]resourceencryption

(disabled)....................................................................................................................... 47

--[no]proxy [type][;regex]

(disabled) ...................................................................................................................... 47

--[no]tamperingdetection

(disabled) ...................................................................................................................... 47

Code Generation ............................................................................................................................................................ 47 --addreference ....................................................................................................................................... 48 --[no]instrument [regex] --[no]emptymethods --[no]deadcode [regex]

(disabled) ....................................................................................................................... 48

(enabled) .............................................................................................................................. 48 (disabled) .......................................................................................................................... 48

7 --[no]seal

(disabled) ............................................................................................................................................ 48

--[no]cleanattrs

(disabled) ........................................................................................................................ 48

--[no]enumremoval

(disabled) ............................................................................................................................... 48

--[no]constremoval

(disabled) ................................................................................................................................ 48

--[no]disgregateremoval --[no]inlineexpansion

(disabled) ........................................................................................................................ 48 (disabled) ........................................................................................................................... 49

--moduleinitializer [method] ...................................................................................................................................... 49 --[no]debug [source]

(disabled) .............................................................................................................................. 49

Output Files .................................................................................................................................................................... 50 --output ............................................................................................................................................................ 50 --pdb ................................................................................................................................................................. 50 --pdbpwd ............................................................................................................................................... 50 --logfile ............................................................................................................................................................. 50 --mapout [file] ............................................................................................................................................................ 50 --makeproject [file] .................................................................................................................................................... 50 Input Files ....................................................................................................................................................................... 50 --keyfile ............................................................................................................................................................ 50 --keyname .............................................................................................................................................. 50 --keypwd ................................................................................................................................................ 51 --keystore ......................................................................................................................................................... 51 --keypass ................................................................................................................................................ 51 --keyalias ........................................................................................................................................................ 51 --storepass ............................................................................................................................................. 51 --rules ............................................................................................................................................................... 51 --mapin ............................................................................................................................................................. 51 --project ............................................................................................................................................................ 51 Configuration File ........................................................................................................................................................... 52 Processing Phases........................................................................................................................................................... 55 Obfuscation Agent .......................................................................................................................................................... 56 Rules File......................................................................................................................................................................... 58 Rules Element ............................................................................................................................................................ 58 Rule Element .............................................................................................................................................................. 58 Custom Attributes .......................................................................................................................................................... 64 ObfuscateAssemblyAttribute ......................................................................................................................................... 64 ObfuscationAttribute ..................................................................................................................................................... 64 Merge and Embed Assemblies ................................................................................................................................. 66

8 Assembly Merging .......................................................................................................................................................... 67 Merging Silverlight and WPF assemblies ........................................................................................................................ 68 Assembly Embedding ..................................................................................................................................................... 69 Symbols Renaming .................................................................................................................................................. 71 Symbols Renaming ......................................................................................................................................................... 72 Unicode Character Set .................................................................................................................................................... 74 Overloaded Renaming .................................................................................................................................................... 74 XAML and BAML Obfuscation ........................................................................................................................................ 75 Advanced XAML Settings ........................................................................................................................................... 75 Silverlight XAML Obfuscation ......................................................................................................................................... 76 Control Flow Obfuscation ........................................................................................................................................ 78 Basic Control Flow Obfuscation...................................................................................................................................... 79 Enhanced Control Flow Obfuscation .............................................................................................................................. 80 Invalid Op-Codes ............................................................................................................................................................ 81 Encryption and Protection ....................................................................................................................................... 83 Code Encryption ............................................................................................................................................................. 84 String Encryption ............................................................................................................................................................ 87 XOR Algorithm............................................................................................................................................................ 87 HASH Algorithm ......................................................................................................................................................... 87 Custom String Encryption ............................................................................................................................................... 88 Inline Values and Array Encryption ................................................................................................................................ 89 Resource Encryption....................................................................................................................................................... 90 Dynamic Proxy Calls........................................................................................................................................................ 92 Tampering Detection ...................................................................................................................................................... 93 Code Generation ..................................................................................................................................................... 94 Dead Code Removal ....................................................................................................................................................... 95 Metadata Optimizations................................................................................................................................................. 95 Automatic Class Sealing ............................................................................................................................................. 95 Removing of Unwanted Attributes ............................................................................................................................ 96 System.Enum Types Removal .................................................................................................................................... 97 Disgregate Removal ................................................................................................................................................... 98 Code Optimizations ........................................................................................................................................................ 98 Inline Expansion ......................................................................................................................................................... 98 Code Instrumentation ............................................................................................................................................ 100 Activating Instrumentation ........................................................................................................................................ 101 Simple Tracing Walkthrough ........................................................................................................................................ 102

9 Creating SimpleTrace Project ................................................................................................................................... 102 Adding stub methods and building the project ....................................................................................................... 104 Creating an Obfuscation Test Project ...................................................................................................................... 104 Instrumenting the TestClient Application ................................................................................................................ 105 MSBuild Babel Task ............................................................................................................................................... 107 The Babel Task .............................................................................................................................................................. 108 Babel MSBuild Project Files .......................................................................................................................................... 111 Task Attributes ............................................................................................................................................................. 113 Using Babel Task in Visual Studio Project ..................................................................................................................... 118 Using Babel Task in Xamarin Studio ............................................................................................................................. 119 Customizing Project File Intellisense in Visual Studio .................................................................................................. 122 Visual Studio Integration ....................................................................................................................................... 123 Post Build Event ............................................................................................................................................................ 124 Project File .................................................................................................................................................................... 124 How to Add an XML Rule File in Visual Studio Project ................................................................................................. 125 Visual Studio Project File Samples ................................................................................................................................ 125 Enable Babel Obfuscation on Release Build Only .................................................................................................... 125 Obfuscate Silverlight XAP Package ........................................................................................................................... 126 Setup Obfuscation for Windows Store..................................................................................................................... 126 Obfuscating .NET Micro Framework Applications ................................................................................................... 127 Obfuscating Windows Phone Applications .................................................................................................................. 128 Handling Packages ................................................................................................................................................. 129 XAP Packages ................................................................................................................................................................ 130 XAP Package Compression ....................................................................................................................................... 130 XAP Skip List ............................................................................................................................................................. 130 APPX Packages.............................................................................................................................................................. 131 APPX Package Signing .............................................................................................................................................. 131 Android APK Packages .................................................................................................................................................. 132 Cross Assembly Obfuscation with Packages................................................................................................................. 132 Advanced Topics .................................................................................................................................................... 133 Satellite Assemblies for Localized Applications ............................................................................................................ 134 PFX Assembly Signing ................................................................................................................................................... 135 Obfuscating x64 Assemblies ......................................................................................................................................... 135 Customize MSIL Encryption .......................................................................................................................................... 136 Cross Assembly Obfuscation ........................................................................................................................................ 138 Cross Assembly Obfuscation in the User Interface .................................................................................................. 139

10 Plugins .......................................................................................................................................................................... 140 Plugin Code Samples ................................................................................................................................................ 141 Custom String Encryption ........................................................................................................................................ 141 Custom Value Encryption ......................................................................................................................................... 141 Merging Custom Code ............................................................................................................................................. 142 Loading Plugins ........................................................................................................................................................ 144 Debugging your Plugin ............................................................................................................................................. 145 Troubleshooting a Broken Application ......................................................................................................................... 146 Obfuscation Tips ........................................................................................................................................................... 147 Appendix A ............................................................................................................................................................ 148 Warning Codes ............................................................................................................................................................. 148 Unicode Character Ranges ........................................................................................................................................... 150 Index ..................................................................................................................................................................... 151

11

Conventions Used in This Manual Various typefaces in this manual identify terms and other special items. These typefaces include the following: Typeface Italic Monospace

Meaning Italic is used for new terms or phrases when they are initially defined and occasionally for emphasis. 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.

12

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 a 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.

13

Software Requirements The following software is required:   

A version of Windows that supports the .NET Framework 4.0/4.6. This can be Windows XP SP3, Windows Server 2003 SP1 (including the R2 edition), Windows Server 2008 (including the R2 edition), Windows Vista, Windows 7 and Windows 8/8.1. .NET Framework 4.0/4.5. 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

14

What’s New • • • •

Extended plugin interface Improved WPF XAML merge and obfuscation Improved Xamarin obfuscation General bug fixes (see Release Notes Bug Fixes)

Babel Obfuscator Release Notes Assembly version 8.9.0.0, File version 8.9.0.0 Enhancements  

Added support for VS 2017 RC Added configurable name prefix (--nameprefix switch)

Bug Fixes  

Fix: Stack trace deobfuscator for generic types Fix: babel.exe cannot parse BAML resource stream warning

The release notes for past releases are available at the following address http://www.babelfor.net/releasenotes

15

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

16

Product Features The main features are listed below:

General Features 

           

Works with Microsoft .NET Framework 1.1, 2.0, 3.5, 4.0, 4.5, 4.6.x, Windows Runtime and Windows Store applications, .NET Micro Framework 3.0, 4.x, Silverlight 3.0 to 5.0, Compact Framework, Windows Phone 7.x/8, Xbox 360 XNA Framework 2.0, 3.0, 4.x, Xamarin Mono for Android and iOS, MonoGame, Unity3D Supports obfuscation of mixed-mode assemblies Selective Obfuscation with XML Rule Files XML Mapping Files Declarative Obfuscation using Custom Attributes Graphic User Interface Visual Studio Post-Build Integration MSBuild and NAnt Integration Supports Command Line Interface Supports Multiprocessor Execution Disables tools like .NET Reflector, Reflexil plug-in, and ILDASM One year of free product updates Custom plugins

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 Supports Incremental Renaming

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 Tampering Detection

Code Instrumentation and Optimization      

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

17

Deployment         

Assembly Merging Assembly Embedding Supports Silverlight XAP Packages Supports Windows Store APPX Packages Supports Android APK Packages Automatic Obfuscation of Satellite Assemblies Automatic Management of XML document files Supports re-sign with PFX and Strong Name Signature Supports decoding of obfuscated stack

18

Feature Matrix Babel is available in 3 editions: Standard, Professional and Enterprise. The following table shows the features included in each edition. Features .NET Framework Support Microsoft .NET Framework from 1.1 to 4.6, Silverlight from 3.0 to 5.0, Compact Framework, .NET Micro Framework 3.0, 4.x, Windows Phone 7.x/8, Xbox 360 XNA Framework from 2.0 to 4.5, Windows Runtime, Xamarin Android and iOS, MonoGame, Unity 3D 64 Bit Support Supports obfuscation of Windows Store APPX Packages, Android APK Packages and Silverlight XAP Packages Mixed Mode Assemblies Custom Plugins 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 Invalid Op-Codes 1 Prevent ILDasm1 String Encryption1 Inline Values and Arrays Encryption Protection Against Reflection Dynamic Proxy Calls (Internal/External Methods) Resource Encryption1 MSIL Encryption1 Anti-Tampering Protection Code Instrumentation and Optimization

1

Refer to Technology Matrix to see .NET Framework compatibility.

Standard

Professional

Enterprise Company

19

Dead Code Removal Automatic Class Sealing and Attributes Cleanup System.Enum Type Removal Constant Fields Removal Disgregate Removal Inline Expansion Code Instrumentation Deployment Strong Name Signature with SNK XML Map Files Generation Supports XML Documentation Files 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 and NAnt Support Parallel Phase Execution Product Maintenance One Year of Product Upgrades

20

Technology Matrix

Mono Android / iOS (Xamarin)

-

Windows Runtime

Windows Phone

-

XNA 4.0 XBOX360

Silverlight

Compact Framework

.NET Micro Framework

.NET Framework 1.1

.NET Framework 2.0 3.x

Edition PRO/ENT

.NET Framework 4.x

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

Obfuscation STD

Symbol Renaming

STD

Generic Types and Methods

STD

XML Rule Files

PRO

Unicode/Custom Characters

PRO

Overload Renaming

PRO

Mixed Mode Assemblies

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 Values and Arrays

PRO

Anti-Reflection Protection

PRO

Dynamic Proxy Calls

PRO

Resource Encryption

ENT

MSIL Encryption

ENT

Anti-Tampering Protection

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

Code Optimization PRO PRO ENT

ENT

Dead Code Automatic Class Sealing, Attribute Cleanup Code Instrumentation System.Enum Type Removal, Const Fields Removal, Disgregate Removal, Inline Expansion Deployment

STD

Strong Name Signature

STD

XML Map Files Generation

PRO

Resign with PFX Files

PRO

Support APPX, APK and XAP

-

-

-

-

-

-

-

-

-

-

-

21

Packages PRO

Assembly Embedding

ENT

Satellite Assemblies

ENT

Assembly Merging

-

-

-

-

-

-

-

-

-

22

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 different licensing schemas to accommodate an increasing number of features and prices:

Single user licenses Single user licenses are   

Standard Professional Enterprise

You can install Babel Obfuscator on your machine(s) for your single use only. This means that a license must be purchased for each developer that uses Babel Obfuscator.

Multi user license The multi user license is the Company license. 

Company

This license is suited for companies with many developers who want to use Babel Obfuscator without any limitation to the number of users who need to access the obfuscation facilities. With the Company license, you can install Babel Obfuscator on an unlimited number of machines and build servers within your company. 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 50% 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, NAnt and Command Line Graphic User Interface

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

23

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

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/Company Licensing The Enterprise/Company 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 and Company editions: General Features 

Custom Plugins

Obfuscation 

XAML and BAML obfuscation

Protection   

MSIL encryption Embedded resource encryption Anti-Tampering Protection

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

24

Standard, Professional, Enterprise and Company 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 and continue to receive new product releases. Company licenses will benefit priority email support.

Licensing FAQ Is your license on a per-developer basis? Yes for Standard, Professional and Enterprise licenses. Each developer must obtain a license. With this license, the developer can install on a primary machine and a portable/laptop. With Company license there are no limit to the number of developers/machine inside your Company where you can distribute the product. 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 if you are the only user that have access to the build. In any way, you need to have the Company license 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 monthly. 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, Enterprise and Company 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

25

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.

26

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 all .NET Framework versions from 1.1 to 4.6, Windows Runtime, Silverlight 3.0 to 5.0, Windows Phone 7.x, Xbox 360 XNA Framework and .NET Micro Framework 3.0, 4.x, Windows Runtime, Xamarin, Mixed Mode Assemblies Graphic user interface Compatible with FIPS standards Full symbols renaming Incremental Renaming Silverlight XAP, APPX and APK Package Support XAML Parsing for Silverlight Applications Assembly Merging Assembly Embedding Embedded Resources Encryption MSIL Encryption Anti-Reflection Protection XAML and BAML Obfuscation Dynamic Proxy Calls to External and Internal Methods Code Instrumentation Enhanced Control Flow Obfuscation Enhanced String Encryption Inline Value and Array Encryption Automatic Class Sealing Anti-Tampering Protection

                

Attributes Removal Code and Metadata optimizations Multiprocessor Execution Performance Improvements Major Fixes on Symbol Renaming and Metadata Verification Log File Output PDB File generation Custom Unicode Obfuscation Character Set Automatic Obfuscation of Satellite Assemblies Public Symbol Obfuscation Revisited Control Flow Obfuscation Improved Overload Renaming Extended XML Rules Files SNK and PFX File Support Extended Command Line Help More than 50 Command Line Options Custom Plugins

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 (methods only) Selective Obfuscation with XML Rule Files Declarative Obfuscation using Custom Attributes MSBuild Integration SNK Strong Name Signature

27

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 [email protected]

28

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.

29

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_8.9.0.0.msi for 32 bit and babel_x64_8.9.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.

30

MAC OSX Setup Babel Obfuscator is available to run on Max OS X. To install Babel Obfuscator under Mac OS X please extract the babel_mac_8.9.0.0.zip package in /Applications/Babel folder and copy in the same folder your license file babel.licenses. Then install Babel.Build.dll into the mono GAC with the following command: sudo gacutil –i /Applications/Babel/Babel.Build.dll

To access babel.exe, you can add /Applications/Babel to the $PATH variable by exporting it to your .bash_profile file. export PATH=$PATH:/Applications/Babel

Create a bash script under /Applications/Babel named babel containing the following lines: #!/bin/bash mono /Applications/Babel/babel.exe "$@"

Save the babel script and enter: chmod +x babel

Now if you open a Terminal windows you can start babel typing: babel myassembly.dll

31

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) 2) 3) 4)

Primary Source Drop Down Primary Source Assembly Input Grid Group Navigation Panel Groups

32

Creating a New Solution File • • •

In the Input Grid select the File column in the first available row and click the browse button. Browse for a Primary Source Assembly: a .NET Framework EXE or DLL file or a XAP/APPX Package. Save your project by selecting from the main menu: File > Save As and 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. You can add more assemblies to your solution by repeating the above steps 1 and 2.

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 Maps, and each one group different additional files.

33

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.

Use the bottom grid navigator bar to remove the selected Primary Source Assembly 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.

34

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 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 propagate 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. 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.

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.

35

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.

1) Primary Source Assembly obfuscation progress

36

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.

37

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.

38 Deobfuscated Stack Trace and Overloaded Renaming When overloaded renaming is enabled Babel renames all the methods of a given type with the same name as long as this is permitted by CLR rules. This makes more difficult to reconstruct the correct stack trace from the obfuscated one because each obfuscated name might have more than one match: Acme.ViewModel.ViewModel.MainViewModel.LoadData() => Acme.ViewModel.ViewModel.MainViewModel.CloseWindow() => Acme.ViewModel.ViewModel.MainViewModel.CleanUp() Acme.ViewModel.ViewModel.MainViewModel.get_Message()

In this case Babel will show in every line of the obfuscated stack trace, all the possible methods matched to the main guess.

39

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 [...] [options]

The is the target assembly or an assembly package (whether an APPX or XAP package) that we want to obfuscate. This parameter 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 […] 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.

40

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 several 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 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 (v) Sets the console output verbosity level when 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 obfuscate myapp.exe types, properties and methods with the agent analysis enabled.

--nowarn Suppress the notification of one or more warning messages. The 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.

41

--[no]warnaserror [warn list] Specifies a list of warnings that should be treat as errors halting the obfuscation process. The [warn list] is an optional comma-delimited list of the warning ID to which the warnaserror option applies. 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 Adds the specified directory , to the list of folders where Babel searches for referenced assemblies.

--take 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:

This option may be specified multiple times. Examples: babel package.xap --take ".*gui\.dll" --take ".*engine\.dll"

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

--skip 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 Set XAP package compression level (default: 6).

(6)

42

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 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 want 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.*"

--[no]removekey Removes the strong name signature from the target assembly.

--dbghelpdlldir Set the directory to dbghelp.dll.

--trace Enable obfuscation tracing for symbols whose signature matches the given regular expression.

43

--randomseed Set the seed used to initialize the random number generator.

Plugins --plugin Set Babel plugin file path. This option may be specified multiple times. (see Plugins)

--argument Set plugin argument as key value pair. This option may be specified multiple times.

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.

--[no]copyattrs [regex]

(enabled)

When this option is enabled, all the assembly level attributes of each input assembly are copied into the target assembly. An optional regular expression can be specified to allow the merging of duplicate attributes that match the given regular expression.

--embed 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) If disabled, types are not renamed.

(enabled)

44

--[no]events (e)

(enabled)

If disabled, events are not renamed.

--[no]methods (m)

(enabled)

If disabled, methods are not renamed.

--[no]parameters (r)

(enabled)

If disabled, parameters 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 = that configures the renaming process. The configuration options accepted are:    

keys = {On/Off} res = {On/Off} strip = {On/Off} manual = {On/Off}

Whether to enable renaming of dictionary keys Whether to enable renaming of BAML/XAML resources Whether to strip line information or white spaces Whether to use manual symbol renaming

--[no]virtual

(enabled)

If disabled, virtual members such as methods, properties and events, are not renamed.

--[no]overloaded

(disabled)

If enabled, Babel uses the same name for two or more methods of the same type during obfuscation.

--[no]flatns (n)

(enabled)

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]

(enabled)

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

(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.

45

    

types= methods= properties= fields= events=

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

--nameprefix [prefix] Set the name prefix of renamed symbols. Optionally key value pairs can be entered to set the prefix of types, methods, properties, fields, events and parameters separately.      

types=prefix methods=prefix properties=prefix fields=prefix events=prefix parameters=prefix

Example: babel.exe myapp.exe --nameprefix types=$Name_ --nameprefix methods=M_

The special value $Name is replaced with the original symbol name. The $Name prefix can be used to debug renaming issues.

--[no]xmldoc [file|regex]

(enabled)

Whether to update the target assembly XML documentation by filtering all renamed symbols. Optionally the XML document file path or a regular expression can be specified. If the file name or the regular expression match the XML documentation file name of a merged assembly, the XML documentation of the merged assembly will be merged into the XML documentation of the target assembly.

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 = can optionally be entered to configure code scrambling. The configuration options accepted are: Produces verifiable MSIL code     

goto = {On/Off} switch = {On/Off} case = {On/Off} if = {On/Off} call = {On/Off}

Whether to insert irrelevant branches Whether to enable switch scrambling Whether to hide case constants Whether to enable if scrambling Whether to enable random calls

46

 

value = {On/Off} token = {On/Off}

Whether to use value encryption Whether to enable emission of method tokens

Produces not verifiable MSIL code 

underflow={On/Off}

Whether to generate stack underflow

--iliterations 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 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.

47

--[no]valueencryption [key=value]

(disabled)

This option enables the encryption of inline constant values and arrays. Key-value pair = can optionally be entered to enable or disable the encryption of some defined types. The configuration options accepted are:     

int32 ={On/Off} int64 = {On/Off} single = {On/Off} double = {On/Off} array ={On/Off}

Whether to encrypt Int32 values Whether to encrypt Int64 values Whether to encrypt Single values Whether to encrypt Double values 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.

--[no]tamperingdetection

(disabled)

Whether to enable anti tampering detection.

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.

48

--addreference Add existing assembly file to the list of references. This option can be specified multiple times

--[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: 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 (no) the removal of unwanted attributes. The parameter is a regular expression that match the unwanted attribute type full name. This option can be specified multiple times.

--[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]disgregateremoval Enable or disables the removal of property and event metadata information whenever possible.

(disabled)

49

--[no]inlineexpansion

(disabled)

Code inline expansion will allow to substitute a call to method with the body of the method inline.

--moduleinitializer [method] Add module initializer code. Optionally a static method signature with no parameters can be specified which will be called after the module loads.

--[no]debug [source]

(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. A debug symbol store can optionally be specified. Examples: --debug srv*c:\Symbols*http://msdl.microsoft.com/download/symbols

50

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

--output 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 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.

--pdbpwd Set debug information file password. The password will be used to encrypt the source code file names stored into PDB.

--logfile 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 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 ).

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

51

--keypwd 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.

--keystore Set the android keystore location. This option can be set to resign the obfuscated APK package. babel.exe --keystore debug.keystore --keypass android --storepass android --keyalias androiddebgkey

--keypass Set the android keystore password.

--keyalias Specifies the android keystore alias.

--storepass Set the android store password.

--rules 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 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 Start the obfuscation using the project file specified.

52

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. It is possible to change the babel.exe default values from Babel Obfuscator user interface by opening the Options dialog and choosing the Settings node:

The following table shows all available configuration properties: Name AssemblySearchDirectories AutomaticClassSealing BabelProjectAddNewLineOnAttributes CleanupUnwantedAttributes ConsoleForeColorDebug ConsoleForeColorError ConsoleForeColorInfo ConsoleForeColorWarning ConsoleHighlight ConstFieldsRemoval ControlFlowAddBranches ControlFlowAddMethodToken ControlFlowAddSwitchStatement ControlFlowChangeIfStatement ControlFlowComplexifyDecryptStringCalls ControlFlowEncryptSwitchValue ControlFlowHideCaseConstants ControlFlowIterationCount

Default Value empty True False True DarkGray Red White Yellow True False True False False False False False False 3

Type System.Collection.Specialized.StringCollection System.Boolean System.Boolean System.Boolean System.ConsoleColor System.ConsoleColor System.ConsoleColor System.ConsoleColor System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Int32

53

Name ControlFlowObfuscation ControlFlowRandomCall ControlFlowStackUnderflow CopyAttributes DeadCodeElimination DeadCodeRemovalWhipeoutObjectVirtuals DisableWarnings DisgregateRemoval DynamicProxy DynamicProxyCallFilters EmitInvalidOpcodes EmitInvalidOpcodesMode EnumTypeRemoval ExperimentalFeature FlattenNamespaces GenerateDebug Instrument InstrumentEmptyMethods Internalize MakeAppxExeOptions MakeAppxExePath MapFileNameEncoding MinimumEventNameLength MinimumFieldNameLength MinimumMethodNameLength MinimumNameLength MinimumPropertyNameLength MinimumTypeNameLength MsilEncryption ObfuscateEvents ObfuscateFields ObfuscateMethods ObfuscateProperties ObfuscateTypes ObfuscateVirtualFunctions ObfuscateXaml ObfuscationAgent OverloadedRenaming ParallelExecution ProcessReferencedSymbolNames ResourceEncryption ResourceNameSearchFilters SearchSatelliteAssemblies ShowLogo ShowStatistics StringEncryption StringEncryptionAlgorithm SuppressIldasm SuppressReflection UnicodeNormalization UnwantedAttributes ValueEncryption ValueEncryptionInt32 ValueEncryptionInt64 ValueEncryptionSingle ValueEncryptionDouble ValueEncryptionArray VerboseLevel

Default Value True False False True False False empty False none empty False empty False True True False False True False Base64 0 0 0 0 0 0 False True True True True True True False True True True True False True True True True empty True False True False True True True True True 1

Type System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Collection.Specialized.StringCollection System.Boolean System.String System.Collection.Specialized.StringCollection System.Boolean System.String System.Boolean System.Bolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.String System.String System.String (Base64/None) System.Int32 System.Int32 System.Int32 System.Int32 System.Int32 System.Int32 System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Collection.Specialized.StringCollection System.Boolean System.Boolean System.Boolean System.Boolean System.String System.Boolean System.Boolean System.Boolean System.Collection.Specialized.StringCollection System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Boolean System.Int32

54

Name WarningsAsError XamlManualRenamePublic XamlObfuscateResourceKeys XamlStripLineInfo XapCompressionLevel XapSkipList

Default Value empty False True True 6

Type System.Collection.Specialized.StringCollection System.Boolean System.Boolean System.Boolean System.Int32 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: EM0008 EM0010

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

55

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 Merge Input Assemblies Phase Post Reader Phase Build Call Graph Phase Process Rule Phase Agent Phase Dead Code Removal Build Map Phase Code Instrument Code Optimizations

Dynamic Proxy Calls Renaming Tampering Detection Encrypt MSIL Phase Encrypt Values Phase Encrypt String Phase Control Flow Obfuscation Phase Embed Assemblies Phase Encrypt Resources Phase Emit Phase

Command Line Options List of assemblies to process

--rules --agent --deadcode, --cleanattrs --mapout --instrument --seal --enumremoval --constremoval --disgregateremoval --proxy --types, --methods, --properties, --fields, --events --tamperingdetection --msilencryption --valueencryption --stringencryption --controlflow --invalidopcodes --embed --resourceencryption

Description Process XML rules files and Merge input assemblies. Analyze the target assembly Build the method call graph. Process XML rule files Performs Agent tasks Remove unused members Build target map document Enable code instrumentation. Code optimizations

Generate dynamic proxies Rename assembly symbols Add tampering detection code Encrypt MSIL Encrypt values and arrays Encrypt all strings Scramble MSIL code Embed assemblies Encrypt embedded resources 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.

56

Merge Input Assemblies

Post Reader

Build Call Graph

Process Rules

Obfuscation Agent

Dead Code Removal

Build Map

Instrument Code

Optimizations

Dynamic Proxy Calls

Encrypt Values

Control Flow Obfuscation

Renaming

Tampering Detection

Encrypt MSIL

Encrypt Strings

Embed Assemblies

Encrypt Resources

Emit

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: Classes .*RedBlackTree Rename RedBlackTree class.

57

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. .*RedBlackTree Serializable types Ignore Serializable types tasks for RedBlackTree.

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 TaskNameList that contains a list of comma separated task names. In this case 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. If the name list is empty, all the agent tasks are affected by the rule.

List of available Agent task names: Task name string Reflected enums Serializable types Reflected strings Reflected types Type consumed by attributes Exposed attributes XAML analyzer WinRT types Dynamic language Table 2 Agent task names

Description Ignore enum types that are consumed by reflection methods Do not rename serializable types Discover symbol name strings consumed by reflection methods Do not rename types consumed by reflection methods Do not rename types consumed by attributes Ignore symbols that expose specific attributes Parse XAML resources to discover types that should not be obfuscated Do not rename WinRT types Do not rename symbols used by dynamic language runtime

58

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 . This list is enclosed by the element that is also the root document element.

Rules Element

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

Value 2.0

Required No

Type System.String

targetAssembly

-

No

System.String

Description Define the current schema version and must be set to "2.0" 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 is selected by a rule that targets a feature or a group of features, those features will be enabled or disabled for that particular symbol based on the value (true or false) assigned to the attribute exclude. When there are two or more rules targeting the same feature for a given symbol, the last rule declared wins.

Rule Element The Rule element is used to configure an obfuscator feature. The obfuscator feature is indicated by the name assigned to the feature attribute. ...

The Rule element accepts the following attributes: Attribute name exclude

Is Mandatory Yes Yes

Default -

feature

No

default (renaming)

applyToMembers

No

False

Description Friendly rule name Whether to exclude all the symbols that match the rule. The obfuscator feature name as given in Table 4 Obfuscator feature table 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). The obfuscator feature strings are fixed. All the supported feature names are listed in the following table:

59

Feature all default agent control flow dead code dynamic proxy merge msil encryption msil encryption get stream renaming resource encryption string encryption string encryption encrypt method string encryption decrypt method value encryption instrumentation instrumentation on entry method instrumentation on exit method instrumentation on exception method optimizations xaml

Description All obfuscator features Member names obfuscation Obfuscation agent Control flow obfuscation Dead code removal Dynamic proxy calls Assembly merge MSIL encryption Declare get source stream method Member names obfuscation Embedded resources encryption String encryption Defines string encrypt method Defines string decrypt method Inline values and arrays encryption Code instrumentation Defines code instrumentation on entry method Defines code instrumentation on exit method Defines code instrumentation on exception method Metadata optimizations XAML BAML obfuscation

Table 4 Obfuscator feature table

!

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. - 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. - 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. - 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.:

The regular expression should match one of the following symbols format: •

Types: Fully qualified type name Acme.Entities.AcmeEntities

60 Where Acme.DataMining is the namespace name and AcmeEntities is the type name. •

Methods: Acme.Entities.AcmeEntities::CreateOrder(DateTime, Int32) : Void Where CreateOrder(DateTime, Int32) : Void is the method signature.



Properties: Acme.Entities.AcmeEntities::Orders : IQueryable



Fields: Acme.Entities.AcmeEntities::_orders : IQueryable



Events: Acme.Entities.AcmeEntities::OrderAdded : EventHandler

- 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. System.SerializableAttribute - Specifies a list of fully-qualified type names. If the target has one of these base types, the rule matches. This element may have the Boolean attribute onEnclosingType. If set to false, the base types are checked on the target type itself. Otherwise, the base types are checked on the target symbol enclosing type. - Specifies a list of fully-qualified interface type names or method signatures. If the target implements at least one of these interface type or method override, the rule matches. This element may have the Boolean attribute onEnclosingType. If set to false, the interface types are checked on the target type itself. Otherwise, the interface types are checked on the target symbol enclosing type. 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. Methods SQLUtils.DataWriter::* true 6 Encrypt all methods of the DataWriter class.

61

Follow the list of property elements supported by each feature: Feature agent

Element TaskNameList

Type System.String

merge

Internalize

System.Boolean

CopyAttributes

System.String

NoCopyAttributes

System.String

Internalize

System.Boolean

DisableOverloading

System.Boolean

DisableUnicode

System.Boolean

RenameParameters

System.Boolean

NameLength

System.Int32

NamePrefix

System.String

MinInstructionCount

System.Int32

ManInstructionCount

System.Int32

IlIterations

System.Int32

EmitIvalidOpcodes

System.Boolean

ChangeIfStatement

System.Boolean

AddSwitchStatement

System.Boolean

ScrambleControlFlow

System.Boolean

MaxSwitchTargets

System.Int32

HideCaseConstantExpressions

System.Boolean

AddMethodToken

System.Boolean

StackUnderflow

System.Boolean

renaming

string encryption

control flow

Description List of comma separated agent task names. If true, all types that match the rule have their visibility changed to internal. List of comma separated fully qualified type names and/or regular expressions. List of comma separated fully qualified type names and/or regular expressions. If true, all types that match the rule have their visibility changed to internal. Whether to disable overloaded renaming. Whether to disable Unicode names. Whether to rename method parameters. Set the renamed symbol name length. Set renamed symbol name prefix. Threshold for method minimum instruction count. Threshold for method maximum instruction count. The number of iterations to use in the control flow obfuscation algorithm. If true, invalid op-codes are inserted into the method definition. If true, obfuscate if statements. If true, switch statements are inserted into method definition. Whether to produce spaghetti code inserting irrelevant branches. Set the maximum number of switch case targets in the switch control flow obfuscation. If true, hide the calculated constant values in switch control flow obfuscation. If true, load method token instructions are inserted inside the method body. Whether to enable stack underflow instructions generation

62

msil encryption

dead code resource encryption optimizations

UseValueEncryption

System.Boolean

RandomCall

System.Boolean

MinInstructionCount

System.Int32

ManInstructionCount

System.Int32

Cache

System.Boolean

MinInstructionCount

System.Int32

ManInstructionCount

System.Int32

Source

System.String

ClassSealing

System.Boolean

UnwantedAttributes

System.Boolean

EnumRemoval

System.Boolean

ConstRemoval

System.Boolean

DisgregateRemoval

System.Boolean

Whether to encrypt switch jump table values (available only when value encryption is enabled). Whether to generate random calls jump table (available only when switch control flow is enabled). Threshold for method minimum instruction count. Threshold for method maximum instruction count. If true, the encrypted method is cached so that the compilation process is run only the first time the method is used. Threshold for method minimum instruction count. Threshold for method maximum instruction count. MSIL-encrypted data source name Whether to enable class sealing optimization Whether to enable removal of unwanted attributes Whether to enable removal of System.Enum type Whether to enable removal of constant fields Whether to enable removal of properties and event metadata

Table 5 Feature properties

- Any useful rule description

The following example shows the content of an XML rule files. *Properties* Do not obfuscate Properties namespace symbols. Fields, StaticFields System.SerializableAttribute Do not obfuscate fields of serializable types.

63

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.

64

Custom Attributes Babel supports declarative obfuscation using the custom attributes System.Reflection.ObfuscationAttribute and System.Reflection.ObfuscateAssemblyAttribute provided by the .NET Framework starting from version 2.0. This section explains the usage of custom attributes to customize the obfuscation process.

ObfuscateAssemblyAttribute The System.Reflection.ObfuscateAssemblyAttribute, is an assembly-level attribute that 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 that will use obfuscation rules to rename all public symbols. The following code example shows how to mark an assembly private: using System; using System.Reflection; [assembly: ObfuscateAssembly(true)]

ObfuscationAttribute The System.Reflection.ObfuscationAttribute attribute can be used on assembly members like: types, method, events, properties and fields to configure the action taken for a specific obfuscation feature. The attribute has a string Feature property that is used to map a 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. Exclude: indicates whether the obfuscation feature should be excluded for the associated member. ApplyToMembers: specifies whether the action taken by the obfuscator for the associated type should be applied to all its members. StripAfterObfuscation: 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) {

65

}

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();

You can set a list features in the feature string: [Obfuscation(Feature = "renaming,string encryption", Exclude = true)] For obfuscation features that have properties, Babel support an extended feature definition where a list of key value pairs can be specified after the name of the feature: [Obfuscation(Feature = "msil encryption:Source=opt;Cache=true", Exclude = false)] This allow to configure code encryption for the member targeting the ObfuscationAttribute and set the code encryption features properties Source and Cache.

66

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.

67

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 [...] [options]

There are several options that can be used to configure merging at command line and with MSBuild: --[no]copyattrs [regex]: When enabled, force Babel to copy all assembly-level attributes into the primary assembly. Note that any duplicate attribute type having AttributeUsage[AllowMultiple = false] will be discarded. At the command line it is possible to specify an optional regular expression to match the attribute full name that should be merged. For example, the following command: --copyattrs .*InternalVisibleToAttribute Will configure Babel to merge all InternalVisibleToAttribute attributes found in merged assemblies. All other attributes will be skipped. It is possible to specify multiple attributes filters using many copyattrs commands: --copyattrs .*InternalVisibleToAttribute --copyattrs .*AssemblyMetadataAttribute If you want to disable the copying of assembly-level attributes, just enter at command line: --nocopyattrs And no assembly-level attribute will be merged into the target assembly. If you have enabled assembly-level attributes copy at command line or MSBuild, you can use XML rules to filter the attributes to be copied or excluded. There are two rule properties in merge feature you can use to filter assembly-level attributes: These are CopyAttributes and NoCopyAttributes properties. Each property take a regular expression that will be used to match the assembly-level attribute full type name.

Assembly * .*TypeLibVersion

The CopyAttributes filter expression is exclusive i.e.: if the filter doesn’t match the fully qualified attribute type name, the attribute will not be merged. The NoCopyAttributes filter will allow you to select all the attributes that will not be copied, all the other attributes will be merged into the target assembly. --[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 ensures name mangling, improving the overall obfuscation statistics.

68

This option is disabled by default because changing type visibility will prevent the merged types from being consumed outside of the primary assembly. You can enable this option if the merged types are intended to be used only by the primary assembly. If you have enabled the internalize option at command line or with MSBuild, you can internalize types whose fully qualified name match a regular expression using XML rules. For instance, the following rules will merge and internalize all the types defined in Utilities namespace. Utilities.* true Merge and internalize all types in Utilities namespace.

Babel processes rules in the order in which they are declared in the rules file. Each rule for a given feature can override the previous defined rule. You can selectively merge types with XML rules using the merge feature setting the exclude attribute to true:

Although this might break the target assembly because Babel does not perform any integrity check on the resulting assembly. So if you define a rule to prevent the merge of a type instantiated somewhere in the code, Babel will fail to process the assembly with an error similar to the following one: An error occurred during phase 'Merge': Error merging type Acme.ViewModel.MainViewModel Inner Exception: Error merging type Acme.ViewModel.MainViewModel Inner Exception: Error merging method System.Void Acme.ViewModel.MainViewModel::.ctor() Inner Exception: Error processing instruction IL_0030: newobj System.Void Acme.ViewModel.Internal.ModelFactory::.ctor(Acme.ViewModel.MainViewModel) Inner Exception: Cannot resolve type: Acme.ViewModel.Internal.ModelFactory [Acme.ViewModel.dll] In this case, if you want to reduce the size of the merged assembly, better to use Babel Obfuscator dead code removal feature.

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

69

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 especially 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.

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:

70 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 require 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: babelRules.xml Assembly EmployeeTracker.EntityFramework.dll true false Assembly EmployeeTracker.Fakes.dll false false

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.

71

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 make 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.

72

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 Whether to enable type renaming. --methods Whether to enable 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 Whether to enable 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 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, consider lowering the visibility of your public types to internal.

73

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

After renaming

74

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: –

Where and 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

75

XAML and BAML Obfuscation Silverlight and Windows Presentation Foundation (WPF) applications use 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 obfuscators 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.

Advanced XAML Settings 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 [=] Admitted key value pairs are: Key keys

Value On/Off

Default Off

manual res strip

On/Off On/Off On/Off

Off Off Off

Description Whether to enable renaming of static resource dictionary keys Whether to use manual symbol renaming Whether to enable renaming of resource names Whether to strip line information/white spaces in BAML/XAML

Available BAML/XAML BAML/XAML BAML/XAML BAML/XAML

Keys parameter when enabled will allow Babel to rename static resource key names. This will increase the obfuscation of XAML/BAML code. 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. Res enables the obfuscation of the XAML/BAML resource names, making it more difficult to understand the original purpose of a resource file.

76

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

Silverlight XAML Obfuscation XAML renaming ensures a high percentage of symbol renaming and therefore helps improve the overall obfuscation. Babel can remove 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):

And after obfuscation (1656 bytes):

The options used to produce this result were: --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.

78

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 several irrelevant branches, add multiple switch instructions without changing the behavior of the method so that is very difficult to analyze after decompilation.

79

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 several 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 . Increasing the value may result in an increase of the number of branches inserted. The 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 does not always result in an increased number of jumps.

80

The following graphs show an average number of jumps inserted (vertical axes) varying with the number of iterations 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 16 14 12 10 8 6 4 2 0

2,596 methods scrambled

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Average number of jump inserted

16 14 12 10 8 6 4 2 0

Delta

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Average number of jump inserted

Delta

It is not recommended to increase the 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 keyvalue pairs to the controlflow command line option: --controlflow [=] Admitted key value pairs are: Key goto switch case if call Value token underflow

Value On/Off On/Off On/Off On/Off On/Off On/Off On/Off On/Off

IL Verifiable       

Description Whether to insert irrelevant branches Whether to enable switch scrambling Whether to hide case constants Whether to enable if scrambling Whether to enable random calls Whether to use value encryption Whether to enable emission of method tokens Whether to enable stack underflow

81

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

!

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

82

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 opcodes. On the right side the same method is represented by ILDASM disassembler.

.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).

83

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.

84

Code Encryption The MSIL code 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 Do not remove symbols in Utilities namespace

You can change the verbosity of Babel output and see the symbols that have been removed: babel.exe myapp.exe –deadcode –v3 –stat Removing Unused Code... System.Boolean get_IsPinned() System.Boolean get_IsEmpty() System.Void SendMessage() MyApp.Message FormatHeader() MyApp.Address ParseAddress(System.String) System.Generic.Collection`1 get_PendingMessages() System.Boolean get_HasHeader() System.String MakeRelativePath(System.String,System.String) MyApp.IMessage MyApp.Message

In the obfuscation statistics Babel prints a summary of all the symbols removed during the obfuscation process. Dead Code Removal phase, elapsed time 01.453s Removed types: 217 Removed methods: 448 Removed properties: 89 Removed events: 3 Removed fields: 1092

Metadata Optimizations Besides dead code removal Babel provides metadata optimizations. Metadata optimizations aiming at reducing the information contained in the metadata thus improving performance and lessening loading time.

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 nonvirtually.

96

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: Utilities.* false

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

Optionally a regular expression can be specified to match the unwanted attribute type full name: babel.exe myapp.exe --cleanattrs System.Diagnostics.*Attribute

This will remove all custom attribute types defined in the System.Diagnostics namespace.

97

A predefined list of unwanted attributes 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: True \[mscorlib\]System.Runtime.CompilerServices.CompilerGeneratedAttribute \[mscorlib\]System.Diagnostics.DebuggerDisplayAtrribute

Each string element of the UnwantedAttributes collection, defines a regular expression that match the custom attribute full type name in the following form: [assembly name]FullTypeName

So, for instance the simplest regular expression that match DebuggerStepThroughAttribute is the following: \[mscorlib\]System.Diagnostics.DebuggerStepThroughAttribute

Note that we have to use the escape ‘\’ character before the open and close brackets since these are reserved to regular expression syntax. The assembly name is not mandatory and can be omitted. 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: Utilities.* false

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. Utilities.* false

98

Disgregate Removal This optimization performs the removal of properties and events information from the respective metadata tables. The properties and events removed, will have their get_ and set_ or add_ and remove_ methods converted to standard methods. This optimization reduces the metadata size and when combined with renaming produce a better obfuscation making more difficult to reconstruct the original property. To enable properties and event metadata removal enter at command line: babel.exe myapp.exe --disgregateremoval

You can selectively enable or disable properties and events disgregation using XML rule as follow: Utilities.* false

Code Optimizations Inline Expansion Inline expansion will allow to substitute the call to a method with the instructions in its body inline thereby saving the overhead of function invocation. To enable inline expansion you need to target the methods that should be expanded inline. This can be done using the System.Reflection.ObfuscationAttribute directly on the method: [Obfuscation(Feature = "inline", Exclude = false)] public void Info(string message) {



Or by adding an obfuscation rule to the method or type you want to be expanded:



99 AcmeDataMining.Logger::Info(String) : Void True

Then to enable inline expansion processing, you have to check the Inline Expansion checkbox in the Optimization panel:

Or enter at command line the global switch --inlineexpansion: babel.exe myapp.exe --inlineexpansion --stat

The obfuscation statistics will show the number of inlined methods and how many (expansion) occurred: Optimization phase, elapsed time 00.270s Sealed types: 0 Inlined methods (expanded): 266 (736)

100

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.

101

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 , [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 contain 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)

102

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: Methods SimpleTracer.Tracer.OnEntry* Methods SimpleTracer.Tracer.OnExit* Methods SimpleTracer.Tracer.OnException*

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 { }

103

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)); }

104

}

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 = 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.

105

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:

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 1000 1000 1000

/ / / /

(5! (4! (3! (2!

-

1) 1) 1) 1)

= = = =

8 43 200 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)

106 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.

107

MSBuild Babel 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 under the system Global Assembly Cache.

108

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

Consider the following very simple C# project made by one executable assembly that references one DLL library. We’ll use this sample to describe how to make an MSBuild project using 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 assembly HelloLib.dll: 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.

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:

109

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: HelloWorld HelloLib

110

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 and the HelloLib.dll, but we didn’t use the Babel task yet. Suppose that we want to obfuscate only the HelloWorld.exe assembly. This can be easily achieved by adding to the Build target the Babel task declaration:

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 can 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:

You can add more attributes to customize the obfuscation process. 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: 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:

Or you can instruct Babel task to merge the referenced assembly HelloLib.dll into the primary assembly by adding the MergeAssemblies attribute:

111

The Internalize attribute changes the visibility of Hello class so that it will be visible only to types defined internally to the merged assembly. This ensures that all the internalized types can be subsequently obfuscated. If you want to merge multiple libraries into the primary assembly you need to specify the names of the libraries separated by a semicolon: MergeAssemblies="$(LibName1).dll;$(LibName2).dll"

Now suppose that you want 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.

The babelRules.xml file is defined as follow: Methods HelloLib.* true Encrypt HelloLib methods.

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: myapp.exe true true true false 3

112 None myapp.exe false true .* true false 2 true false true false true true false true;token=false;underflow=false;goto=true;if=true;switch=true;case=true true true true false true

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.

113

Task Attributes

and Emb ed

Miscellaneous

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 EnableObfuscation

String Boolean

ShowLogo

ShowLogo

Boolean

ShowStatistics

ShowStatistics

Boolean

VerboseLevel XapCompressionLevel

VerboseLevel XapCompressionLevel

Int32 Int32

EnableObfuscationAgent

EnableObfuscationAgent

Boolean

SatelliteAssemlies

BabelRulesFileName SatelliteAssemlies

String String

SearchDirectories

SearchDirectories

String

TakeFiles

BabelTakeFiles

String

SkipFiles

BabelSkipFiles

String

NoWarnings

NoWarnings

String

WarningsAsErrors

WarningsAsErrors

String

DbgHelpDllDir

DbgHelpDllDir

String

QuickRules MergeAssemblies

QuickRules MergeAssemblies

String String

Full path to babel.exe tool Global switch to enable or disable the obfuscation process Outputs Babel copyright information Whether you want Babel to show obfuscation statistics Console output verbosity XAP package compression level Whether to enable agent task processing BabelRules.xml List of assembly files to process as satellite assemblies List of directories where Babel searches to resolve referenced assemblies List of regular expressions to match against deployed XAP package assemblies that should be obfuscated. This property is equivalent to the –take Babel command line switch. 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. List of warning message codes to ignore Any messages that would ordinarily be reported as warnings are instead reported as errors, and the obfuscation process is halted. Set the path to the dbghelp.dll List of quick rule definitions List of assembly files to merge into the primary assembly

Renaming

114

Task Attribute

Babel.Build.targets

Type

Description

Internalize

MergeInternalize

Boolean

CopyAttributes

MergeCopyAttributes

Boolean/String

EmbedAssemblies

EmbedAssemblies

String

Whether merged types have their visibility restricted to the assembly Whether assembly-level attributes of merged assemblies are copied into the target assembly. List of assembly files to embed into the primary assembly

ObfuscateTypes

ObfuscateTypes

Boolean

ObfuscateEvents

ObfuscateEvents

Boolean

ObfuscateMethods

ObfuscateMethods

Boolean

ObfuscateParameters

ObfuscateParameters

Boolean

ObfuscateProperties

ObfuscateProperties

Boolean

ObfuscateFields

ObfuscateFields

Boolean

ObfuscateXaml

ObfuscateXaml

Boolean/ Key=Value

VirtualFunctions

VirtualFunctions

Boolean

OverloadedRenaming

OverloadedRenaming

NameLength

NameLength

Boolean/ Key=Value Int32

NamePrefix

NamePrefix

String

FlattenNamespaces

FlattenNamespaces

Boolean

XmlDoc

XmlDoc

Boolean/String

Whether to obfuscate the names of types Whether to obfuscate the names of events Whether to obfuscate the names of methods Whether to obfuscate the names of parameters Whether to obfuscate the names of properties Whether to obfuscate the names of fields (Boolean) Whether to obfuscate the symbols inside XAML/BAML resources. Whether to enable virtual member name obfuscation Whether to overload method names when possible Set the minimum name string length to use when generating obfuscated symbols names Set obfuscated symbol name prefix Whether namespace names information should have their types’ visibility restricted to the assembly Set the pat to XML documentation file

Encryption and Protection

Control Flow Obfuscation

115

Task Attribute

Babel.Build.targets

Type

Description

UnicodeNormalization

UnicodeNormalization

Boolean/String

Whether to obfuscate member names using Unicode symbols

ControlFlowObfuscation

ControlFlowObfuscation

Boolean Key=Value

Whether to enable MSIL control flow obfuscation

ControlFlowIterations ILIterations Itertions

ILIterations

Int32

Number of iterations used in the control flow obfuscation algorithm.

EmitInvalidOpcodes

EmitInvalidOpcodes

Boolean

Whether to emit invalid opcodes

MsilEncryption

MsilEncryption

Boolean/String

StringEncryption

StringEncryption

Boolean/String

ValueEncryption

ValueEncryption

ResourceEncryption

ResourceEncryption

Boolean/ Key=Value Boolean

DynamicProxy

DynamicProxy

Boolean/ Key=Value

SuppressIldasm

SuppressIldasm

Boolean

Whether to enable code encryption for methods that are addressed by the msil encryption feature. Optionally a given regular expression can be specified to encrypt the methods that match their signature Whether to enable encryption of user strings. Optionally the encryption string algorithm name can be specified. Whether to encrypt Inline Values and Arrays Whether to encrypt Resources Whether to wrap calls to external assemblies in proxies generated dynamically Whether to prevent ILDASM from disassembling the obfuscated target

Code Generation

116

Task Attribute

Babel.Build.targets

Type

Description

SuppressReflection

SuppressReflection

Boolean

TamperingDetection

TamperingDetection

Boolean

Whether to prevent tools using reflection from displaying metadata. Whether to enable the generation of tampering detection code

AddReference

AddReference

String

InlineExpansion

InlineExpansion

Boolean

Instrument

BabelInstrument

Boolean/String

InstrumentEmptyMethods

InstrumentEmptyMethods

Boolean

DeadCodeElimination

DeadCodeElimination

Boolean

SealClasses

SealClasses

Boolean

CleanAttributes

CleanAttributes

Boolean/String

EnumRemoval

EnumRemoval

Boolean

ConstRemoval

ConstRemoval

Boolean

DisgregateRemoval

DisgregateRemoval

Boolean

List of assembly files to reference into the primary assembly Whether to enable inline expansion for methods that are addressed by the inline feature (Boolean) Whether to enable code instrumentation. (String) A list of regular expressions to match methods full name that will be instrumented. Whether to enable the instrumentation of empty methods Whether to remove unused methods from the target assembly Whether to seal classes whenever possible (Boolean) Whether to cleanup unwanted attributes. (String) A list of regular expressions can be specified to filter unwanted attributes according their full type name. Whether to enable System.Enum types removal Whether to enable constant fields removal Whether to enable properties and event metadata removal

Input Files

Output Files

117

Task Attribute

Babel.Build.targets

Type

Description

GenerateDebug

GenerateDebug

Boolean

Whether to enable debug symbols generation

OutputFile

BabelOutputFile

String

Obfuscated target file path

PdbFile

PdbFile

String

Debug symbols file path

PdbPwd

PdbPwd

String

Set PDB file password

GenerateLogFile

GenerateLogFile

Boolean

LogFile

BabelLogFile

String

Whether to generate obfuscation log. The file name will be: .log Obfuscation log file path

GenerateMapOutFile

GenerateMapOutFile

Boolean

MapOutFile

BabelMapOutFile

String

InputFile

BabelInputFile

String

KeyFile

KeyOriginatorFile

String

KeyContainer KeyPwd

KeyContainerName SigningCertPassword

String String

AndroidSigningKeyStore

AndroidSigningKeyStore

String

AndroidSigningKeyPass

AndroidSigningKeyPass

String

AndroidSigningKeyAlias

AndroidSigningKeyAlias

String

AndroidSigningStorePass

AndroidSigningStorePass

String

RulesFiles

BabelRulesFiles

String

MapInFiles

BabelMapInFiles

String

Plugins

Plugins

String

Table 6 Babel task attributes

Whether to generate obfuscation map file. The map file name will be: .xml.map Output map file path

The path of the main source assembly (mandatory) Path of the strong-name key file Key container name Strong-name certificate password Android key store file (APK Package) Android key store password (APK Package) Android key store alias (APK Package) Android store password (APK Package) Semicolon-separated list of rules file paths List of XML map files to process List of Babel plugin files

118

Using Babel Task in Visual Studio Project You can obfuscate the assemblies compiled in a Visual Studio project by adding the Babel task in the AfterBuild Target as follows: 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 Visual Studio project file locate the last MSBuild Import element. There you will find the BeforeBuild and AfterBuild targets commented.

4) Add the UsingTask Babel under the Import element and uncomment the AfterBuild target:

5) Insert the Babel task inside the AfterBuild element and add the obfuscation attributes

6) Save the project file and from Visual Studio Solution Explorer, right-click the project node and choose the Reload Project command.

You can now rebuild the solution and see in the Visual Studio Output window the Babel Obfuscator command output:

Using Babel Task in Xamarin Studio Xamarin Studio is a modern development environment for creating applications targeting Android and iOS devices. Because Xamarin Studio build are based on MSBuild, if you have installed Xamarin Studio on

120

Window you can obfuscate your assembly directly in Xamarin Studio by adding the Babel task in the project file. 1) Open your solution in Xamarin Studio and from the Solution panel right click the project node and select Unload

2) Right click the unloaded project and choose Tools then Edit File

3) Append the required UsingTask element to reference the assembly containing the MSBuil Babel task. 4) Add the Babel task inside the AfterBuild Target.



5) Save the changes made to the project file. After reloading the project you can switch to Release build and rebuild your solution. Xamarin Studio will create the .apk package file using the obfuscated assembly created during the build process. Note that UnicodeNormalization and FlattenNamespaces options must be disabled otherwise Xamarin build will raise an errors when compiling the auto-generated Java stub types. If you want to enable namespace flattening, you can set: FlattenNamespaces="a"

This will set the default namespace to ‘a’ for all obfuscated types.

122

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 1x.0\Xml\Schemas\1033” and import it into the Microsoft.Build.xsd file as follow:

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

123

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 consists in launching babel.exe from the post-build event Project Designer page. The second involves the editing of Visual Studio project files and it invokes Babel’s MSBuild task.

124

Post Build Event The simplest way to start Babel Obfuscator from within Visual Studio is using 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 commandline syntax can include any build macro.

Project File Babel Obfuscation can be also added to a Visual Studio (.*proj) file using the MSBuild Babel task. This is not as easy as adding a post-build event but ensures a better tuning. There are two ways you can integrate the Babel task in a Visual Studio project. The first is by adding the Babel task directly into the project file and is described in the previous paragraph (How to Add the Babel Task in Visual Studio). The second involves fewer steps and requires the import of the Babel.Build.targets file distributed with the Babel Obfuscator setup. The Babel.Build.targets target file does nothing but import the Babel task and define some common task properties that can be overridden in the Visual Studio project file. To import the Babel targets into your project file: 1) In Visual Studio Solution Explorer, select the project node, right-click, and from the context popup menu choose the Unload Project command. 2) Right click the unloaded project, and from context popup menu choose Edit. 3) In the XML project file insert after the line:

The following Import declaration:

For example:

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 imports the Babel MSBuild task and defines some common task properties. 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: true

If you want to disable Unicode normalization, you can override this property in your project file by adding after the Import Babel.Build.targets declaration the following lines:

125 false

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 imported through the Babel.Build.targets file in a Visual Studio Project (see 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 and select from the popup menu Add -> New Item… 2) From the Add New Item dialog, select an XML file template and enter into the Name text field: BabelRules.xml. 3) Fill the XML file with rule definitions. 4) Save and build the project.

Visual Studio Project File Samples Once you have imported the Babel.Build.targets file you can further customize the obfuscation process by overriding the properties defined into the Babel.Build.targets file. The full set of properties defined into Babel.Build.targets file is available in Table 7 Babel task attributes. In this paragraph we will see some examples about configuring Babel Obfuscator in a Visual Studio project file.

Enable Babel Obfuscation on Release Build Only You can enable or disable Babel obfuscation according to a particular build configuration. If you want to enable Obfuscation only in Release build you can add the following snippet of XML code in your Visual Studio project file: false true 3 true

When the Debug build is selected, the Babel task is disabled and babel.exe is not executed at the end of the build process. Switching the build configuration to Release will enable the Obfuscation.

126

Obfuscate Silverlight XAP Package To obfuscate a Silverlight XAP package directly, override the AfterBuild target and create the BabelInputFile property inside MSBuild as follow:

The AfterBuild target will create the BabelInputFile property with the correct path to the XAP package.

Setup Obfuscation for Windows Store To obfuscate an application targeting the Windows Store edit the Visual Studio project file and append under the XML comment:

The following MSBuild directives: $(TargetPath)

Alternatively you can add the UsingTask element and access directly all the Babel task properties you want to configure:

This will configure Babel Obfuscator to obfuscate the build output in place, making easy the next deployment step with Visual Studio.

127

Obfuscating .NET Micro Framework Applications Assemblies compiled for .NET Micro frameworks need to be further processed by .NET compilers before being deployed to the target. This additional compilation step is performed to ensure the binary compatibility 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:

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

Please refer to the Technology Matrix to see which obfuscation features are available in the .NET Micro Framework.

128

Obfuscating Windows Phone Applications This sample will show how to setup obfuscation in a Visual Studio 2010 project for a Windows Phone 7.x 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:

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 right 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.

129

Handling Packages Application packages like XAP, APPX and APK are a deployment unit that contains the assemblies, resources and usually a manifest that describes the package structure. Babel Obfuscator can handle the assemblies contained in a XAP, APPX or APK package directly without working with individual assemblies outside the given package. Babel accepts as a primary assembly source the package file and performs the obfuscation of all the assemblies inside the package.

130

XAP Packages In a XAP package, the deployed assemblies are those listed as element in the AppManifest XML file as showed in the following AppManifest.xaml file:

It is common practice to 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.*

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.

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: System.Windows.Controls System.Windows.Data System.Xml.Linq

131

APPX Packages The obfuscation of an APPX package is very similar to that of a XAP file. You can obfuscate an APPX package directly from the command line by entering the APPX file path as follow: babel.exe MyWinStoreApp.appx

Babel Obfuscator will obfuscate all the assemblies inside the package and produce a new APPX package in the BabelOut directory. You can use --take and --skip command line options to set the assemblies to obfuscate. Babel Obfuscator uses the MakeAppx.exe command-line tool distributed with the Windows 8 Development Kit to create a new obfuscated APPX package. If Babel cannot locate the MakeAppx.exe tool path it raises an error during the obfuscation process. In this case the user can specify the full path to the MakeAppx.exe in the babel.exe.config file using the following settings C:\Program Files (x86)\Windows Kits\8.0\bin\x86\MakeAppx.exe

Babel can be configured to pass additional parameters at the MakeAppx.exe command line by adding these options to MakeAppxExeOptions setting: /h SHA512 /v

The above settings can also be changed from the Babel Obfuscator user interface. Please refer to the MakeAppx.exe guide to know all the available switches.

APPX Package Signing Babel Obfuscator does not sign the obfuscated APPX package, so the obfuscated APPX package produced by babel.exe needs to be digitally signed before its distribution. To digitally sign the APPX package you need to run the SignTool.exe command-line tool distributed with the Windows SDK. If you have developed your application with Visual Studio you should have configured your project to sign the APPX package with a PFX certificate. To digitally sign the obfuscated APPX package you can use the PFX certificate and enter the following at the command line: > SignTool.exe sign /v /fd SHA256 /a /f MyAppKey.pfx BabelOut\MyWinStoreApp.appx The following certificate was selected: Issued to: xxxxxx Issued by: xxxxxx Expires: Wed Jan 08 17:18:01 2014 SHA1 hash: 987275F2AC2E14B935B36EEE02C6480FB23B7842 Done Adding Additional Store Successfully signed: MyWinStoreApp.appx Number of files successfully Signed: 1 Number of warnings: 0 Number of errors: 0

Once the APPX package is digitally signed you can run the Windows App Certification Kit to test if the obfuscated APPX package meets the Windows Store requirements and can be deployed.

132

Android APK Packages Babel supports obfuscation of Android APK packages build with Xamarin. To obfuscate an APK package enter at command line the path of the APK package to obfuscate: babel.exe AndroidApp.apk

Babel Obfuscator will obfuscate all the assemblies inside the package and produce a new APK package in the BabelOut directory. You can use --take and --skip command line options to set the assemblies to obfuscate. The obfuscated APK can be re-signed using Babel Obfuscator and entering at command line: babel.exe AndroidApp.apk --keystore debug.keystore --keypass android --storepass android --keyalias androiddebugkey

Babel will start the external tool jarsign.exe available with the Java SDK to resign the obfuscated APK. If you have installed Java and Android SDKs and babel cannot find jarsign.exe and zipalign.exe, please add path of jarsing.exe and zipalign.exe tools to the system environment variable PATH. If you want to sign an APK with the MSBuild Babel task, you can use the following APK signing task attributes: ("StringDecrypter::Decrypt.*", true);

The decryptMethod is the method that will be returned by the interface method IBabelStringEncryptionService.DecryptMethod : MethodDef. Check out the plugins at babelfor.NET for more complex samples.

" " " " " " " " " " " " "

+ + + + + + + + + + + +

144

Loading Plugins You can use your custom plugin by passing the path of the plugin DLL at command line: babel.exe MyTarget.exe --plugin CustomPlugin1.dll --plugin CustomPlugin2.dll

It is possible to define additional plugin arguments using the switch --argument: babel.exe MyTarget.exe --plugin CustomPlugin1.dll --plugin CustomPlugin2.dll --argument arg1=value1 --argument arg2=value2

If you are using the Babel Obfuscator user interface, the Input Grid will allow you to specify a list of plugin for each target assembly in your obfuscation project.

If you are using the Babel MSBuild task in your Visual Studio or Xamarin project, you can specify a list of plugins by adding the Plugins task property as follow:

145

Debugging your Plugin To debug your plugin in Visual Studio, open the plugin project settings and choose the Debug tab. Then under Start Action select Start external program and browse for babel.exe:

Then enter the command line arguments passing the full path the target assembly, the plugin file name and additional command line switches: D:\Projects\AcmeDataMining\bin\Debug\Acme.exe --plugin DesEncrypt.dll --string custom

By pressing F5 you can start babel.exe and hit breakpoints in the plugin code.

146

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 have found a bug in Babel. In this case, contact email support: [email protected] Send all the useful information you can, such as:     

The operating system you are running on and processor architecture (x86 or x64) Babel version and 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.

147

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 run-time, perform all the necessary tests on the obfuscated assemblies.

148

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 CF0001 EI0001 EI0002 EM0001 EM0002 EM0003 EM0004 EM0005 EM0006 EM0007 EM0008 EM0009 EM0010 MG0001 MG0002 MG0003 MG0004 MG0005 MG0006 MG0007 MG0008 OB0001 OB0002 OB0003 OB0004 OB0005 OB0006 OP0001 OP0002 PR0001 PR0002 PR0003 PR0004 PR0005 PR0006 PR0007 PR0008 PR0009

Message Unknown invalid op-code mode: '{0}'. Missing key information, the target assembly strong name was removed. Cannot re-sign assembly. {0} does not represent a strongly named assembly. Methods that return pointers are not supported. {0} Methods with pointer parameters are not supported. {0} Methods with ref or out parameters are not supported. {0} Generic instance method inline tokens are not supported. {0} Inline metadata tokens are not supported. {0} Bad inline token type. Unknown metadata signature calling convention. Generic open types are not supported. {0} Generic parameter types are not supported. {0} Type not supported. {0} 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. Referenced assembly '{0}' has a reference to the merged assembly '{1}'. Resource data '{0}' into {1} has already been added. {0} (Could not resolve… generic warning message) Merging referenced assembly {0} of different version {1}. The expected assembly version is {2}. The merged assembly might not be working properly. The assembly '{0}' has already been merged. The type '{0}' defined in '{1}' was not found in merged scope '{2}'. Merge of mixed mode assembly is not supported: '{0}'. Missing key information, the resource assembly '{0}' strong name was removed. The {0} named '{1}' defined into referenced assembly {2} should not be obfuscated. The virtual {0}: '{1}' defined into referenced module: '{2}' cannot be obfuscated: {3}. Please add an obfuscation rule to prevent the renaming of the symbol. The Unicode character set provided is not valid to rename {0} symbols {1}. The ASCII character set will be used instead. Obfuscation rules are preventing renaming of the public {0} '{1}' defined into referenced module: '{2}': {3}. Found rule conflict for the following symbols: {0}. The '{1}' prevents symbol renaming, while '{2}' requires to rename. The symbols will not be renamed. Could not remove enum(s) '{0}'. Method '{1}' has a duplicate. {0} method '{1}' cannot be inlined. Target already processed by Babel; some problems may occur at runtime or during obfuscation. {0} warning: missing {1} string method. Suppressing MSIL disassembler option is not supported on .NET Framework {0} assemblies. Suppress MSIL disassembler (ildasm.exe) option is not supported. Duplicate encrypt string method found {0}. Duplicate decrypt string method found {0}. String algorithm '{0}' is not supported on .NET Micro Framework assemblies. Algorithm '{1}' will be used instead. Emit invalid op-codes option is not supported on {0} assemblies. The reference "{0}" has a higher version '{1}' than the version '{2}' in the current target.

149 PR0010 PR0011 PR0012 PR0013 PR0014 PR0015 PR0016 SE0001 RU0001 RU0002 RU0003 RU0004 W00001 W00002 W00003 W00004 W00005 W00006 W00007 W00008 W00009 W00010 W00011 W00012 W00013 W00014 W00015

The assembly "{0}" is already present in the list of references. Dynamic proxy call option is not supported on {0} assemblies. Resource encryption is not supported on {0} assemblies. MSIL encryption is not supported on {0} assemblies. Assembly embedding is not supported on {0} assemblies. Suppress reflection option is not supported on {0} assemblies. Invalid ObfuscationAttribute at {0}: {1} Encryption string algorithm {0} could not encrypt string '{1}': {2} Rule '{0}' has an unknown property name '{1}'. Rules file unknown node {0} at line {1}, position {2}, node {3} '{4}'. Rules file unknown attribute at line {0}, position {1}, attribute {2}='{3}'. Unknown feature '{0}'. Could not find debug symbols for {0} Cannot parse {0} resource stream '{1}': {2}. {0} resource stream '{1}'. Cannot resolve property '{2}' duplicate members found: {3} Obfuscation Agent is disabled. Debug symbols not loaded: {0}. 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. Could not delete {0} directory: {1} Could not resolve assembly name '{0}'. The assembly was resolved to '{1}'. Could not find method: '{0}'. Could not use method '{0}' as module initializer. The method must be a static method without parameters. The referenced assembly '{0}' full name differs from the loaded map file '{1}'. Invalid map file assembly name '{0}': {1} Could not resolve assembly '{0}'. Error getting symbols from {0}: {1} Cannot find overridden methods of '{0}': {1}

150

Unicode Character Ranges 0020 00A0 0100 0180 0250 02B0 0300 0370 0400 0500 0530 0590 0600 0700 0780 0900 0980 0A00 0A80 0B00 0B80 0C00 0C80 0D00 0D80 0E00 0E80 0F00 1000 10A0 1100 1200 13A0 1400 1680 16A0 1700 1720 1740 1760 1780 1800 1900 1950 19E0 1D00 1E00 1F00 2000 2070 20A0 20D0 2100

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

007F 00FF 017F 024F 02AF 02FF 036F 03FF 04FF 052F 058F 05FF 06FF 074F 07BF 097F 09FF 0A7F 0AFF 0B7F 0BFF 0C7F 0CFF 0D7F 0DFF 0E7F 0EFF 0FFF 109F 10FF 11FF 137F 13FF 167F 169F 16FF 171F 173F 175F 177F 17FF 18AF 194F 197F 19FF 1D7F 1EFF 1FFF 206F 209F 20CF 20FF 214F

Basic Latin Latin-1 Supplement Latin Extended-A Latin Extended-B IPA Extensions Spacing Modifier Letters Combining Diacritical Marks Greek and Coptic Cyrillic Cyrillic Supplementary Armenian Hebrew Arabic Syriac Thaana Devanagari Bengali Gurmukhi Gujarati Oriya Tamil Telugu Kannada Malayalam Sinhala Thai Lao Tibetan Myanmar Georgian Hangul Jamo Ethiopic Cherokee Unified Canadian Aboriginal Ogham Runic Tagalog Hanunoo Buhid Tagbanwa Khmer Mongolian Limbu Tai Le Khmer Symbols Phonetic Extensions Latin Extended Additional Greek Extended General Punctuation Superscripts and Subscripts Currency Symbols Combining Diacritical Marks Letterlike Symbols

2150 2190 2200 2300 2400 2440 2460 2500 2580 25A0 2600 2700 27C0 27F0 2800 2900 2980 2A00 2B00 2E80 2F00 2FF0 3000 3040 30A0 3100 3130 3190 31A0 31F0 3200 3300 3400 4DC0 4E00 A000 A490 AC00 D800 DB80 DC00 E000 F900 FB00 FB50 FE00 FE20 FE30 FE50 FE70 FF00 FFF0

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

218F 21FF 22FF 23FF 243F 245F 24FF 257F 259F 25FF 26FF 27BF 27EF 27FF 28FF 297F 29FF 2AFF 2BFF 2EFF 2FDF 2FFF 303F 309F 30FF 312F 318F 319F 31BF 31FF 32FF 33FF 4DBF 4DFF 9FFF A48F A4CF D7AF DB7F DBFF DFFF F8FF FAFF FB4F FDFF FE0F FE2F FE4F FE6F FEFF FFEF FFFF

Number Forms Arrows Mathematical Operators Miscellaneous Technical Control Pictures Optical Character Recognition Enclosed Alphanumeric Box Drawing Block Elements Geometric Shapes Miscellaneous Symbols Dingbats Miscellaneous Mathematical Symbols-A Supplemental Arrows-A Braille Patterns Supplemental Arrows-B Miscellaneous Mathematical Symbols-B Supplemental Mathematical Operators Miscellaneous Symbols and Arrows CJK Radicals Supplement Kangxi Radicals Ideographic Description Characters CJK Symbols and Punctuation Hiragana Katakana Bopomofo Hangul Compatibility Jamo Kanbun Bopomofo Extended Katakana Phonetic Extensions Enclosed CJK Letters and Months CJK Compatibility CJK Unified Ideographs Extension A Yijing Hexagram Symbols CJK Unified Ideographs Yi Syllables Yi Radicals Hangul Syllables High Surrogates High Private Use Surrogates Low Surrogates Private Use Area CJK Compatibility Ideographs Alphabetic Presentation Forms Arabic Presentation Forms-A Variation Selectors Combining Half Marks CJK Compatibility Forms Small Form Variants Arabic Presentation Forms-B Halfwidth and Fullwidth Forms Specials

151

Index . .NET Micro Framework, 16, 18, 20, 26, 127, 148 .NET Reflector, 12, 16, 46, 82, 90, 136 .pfx, 50, 51

A Activating Instrumentation, 101 Advanced Topics, 133 Any CPU, 135 APPX, 18, 26, 32, 39, 129, 131, 132 Assembly Merge, 43 Assembly Merging, 17, 19, 21, 26, 67 assembly re-sign, 135 automated build, 12, 27 Automatic Class Sealing, 95

B Babel Task, 107, 108, 118, 124, 125 babel.exe.config, 40, 52, 96, 97, 130, 131 BabelDirectory, 110

C Cache, 85 Code Instrumentation, 100 Code Optimizations, 55, 98 Command Line, 16, 19, 22, 26, 39, 55 Compact Framework, 16, 18, 20 CompilerGeneratedAttribute, 96 compress, 41, 69, 70, 90, 130 Configuration File, 52 Control Flow Obfuscation, 16, 18, 20, 22, 26, 45, 55, 78, 79, 115 Cross Assembly Obfuscation, 132, 138 Custom Attributes, 64 custom string encryption, 88 Custom String Encryption, 88

D Dead Code Removal, 95 DebuggerBrowsableAttribute, 96 DebuggerDisplayAttribute, 96 DebuggerHiddenAttribute, 96 DebuggerNonUserCodeAttribute, 96 DebuggerStepThroughAttribute, 96 DecryptString, 88 Disgregate Removal, 19, 20, 98

Dynamic Proxy Calls, 92 DynamicMethod, 84, 85, 136

E Embed Assemblies, 69 EncrypString, 88 encrypt, 46, 47, 59, 62, 69, 70, 83, 84, 85, 86, 87, 88, 89, 90, 110, 111, 115, 136, 147, 148 Enhanced Control Flow Obfuscation, 80 extended help, 39

F FAQ, 24 Feature Matrix, 18 Features, 15

H hash, 87 HASH Algorithm, 87

I ILDASM, 12, 16, 17, 47, 82 ILMerge, 43 inline expansion, 49, 98, 99 Inline Expansion, 19, 20, 98, 99 Input Files, 50 Intellisense, 122 Invalid Op-Codes, 81

L License File, 24 Licensing, 22, 23, 24, 42 Linq, 130

M MAC OSX Setup, 30 MaxInstructionCount, 85 Metadata, 12, 26, 59, 95 Metadata Optimizations, 95 MinInstructionCount, 85 module initializer, 49 MSBuild, 12, 16, 19, 22, 23, 26, 27, 28, 32, 50, 107, 108, 110, 111, 112, 113, 118, 122, 123, 124, 125, 126, 127 MSIL Encryption, 12, 16, 18, 20, 26, 46, 84

152 Multi user, 22

O Obfuscation Agent, 56 Obfuscation Tips, 147 ObfuscationAttribute, 64, 84, 136 Optimizations, 94 Output Files, 50 Overloaded Renaming, 18, 20, 26, 74

P performance, 70, 83, 136 peverify.exe, 146 Phases, 55 Plugins, 141 Post Build Event, 124 private assembly, 64 Project File, 122, 124, 125

Q quick rule definition, 42

R Renaming, 43, 71 Resource encryption, 90 reverse engineer, 12 Rules File, 58

S Satellite Assemblies, 134 serializable types, 57 Settings, 34, 75 Setup, 29 SHA256, 131 SignTool.exe, 131 Silverlight, 16, 17, 18, 19, 20, 22, 23, 26, 66, 68, 69, 71, 75, 76, 87, 92, 126, 128, 130, 133 SimpleTrace Project, 102 Single user, 22 Source property, 136 Stack Trace, 37 String Encryption, 16, 18, 20, 26, 87, 88

strong name, 34, 50, 135, 147, 148 Strong Named Assemblies, 135 System.Enum Types Removal, 97 System.Reflection.ObfuscateAssemblyAttribute, 64 System.Reflection.ObfuscationAttribute, 64

T Tampering Detection, 93 Task Attributes, 113 Tracing, 102 Tracing Walkthrough, 102 Troubleshooting a Broken Application, 146

U Unicode Character Ranges, 150 Unwanted Attributes, 96 User Interface, 16, 22, 28, 31

V Visual Studio, 2, 11, 13, 16, 19, 22, 23, 27, 102, 111, 118, 119, 122, 123, 124, 125, 126, 128, 131, 134, 135, 146 Visual Studio integration, 123

W Warning Codes, 148 Windows App Certification Kit, 132 Windows on Windows64, 136 Windows Phone, 16, 18, 20, 26, 128 Windows Runtime, 16, 18, 20, 26, 126 WPF, 19, 23, 66, 68, 71, 75, 90

X x64 bit, 29, 82 XAML and BAML Obfuscation, 75 XAP, 17, 22, 26, 32, 39, 41, 42, 69, 75, 113, 126, 128, 129, 130, 131 XapSkipList, 130 Xbox 360, 16, 18, 26 XNA Framework, 16, 18, 26 xor, 87 XOR Algorithm, 87