Compass Security AG Werkstrasse 20 Postfach 2038 CH-8645 Jona

T +41 55 214 41 60 F +41 55 214 41 61 [email protected]

www.csnc.ch

Disassemble .NET Clients

September 7th, 2011

Document Name: Paper_DisassembleDotNetClient_v2.0.docx Version: v1.0 Author(s): Alexandre Herzog, Compass Security AG References: - Date of Delivery: September 7th, 2011 Classification: Article

Disassemble .NET Clients by Alexandre Herzog [[email protected]]

1 Introduction The .NET framework supports several programming languages such as C#, VisualBasic.NET or managed C++. Components written for example in C# can easily be reused in code written in another language supported by the framework. Code from these high-level languages gets compiled to a common Intermediate Language (IL) which runs in the (CLR). Reasons to disassemble such code can be multiple, ranging from interoperability purposes (e.g. understanding how a component without adequate documentation works) to recover lost source code or finding security vulnerabilities.

Disassembling .NET clients for security purposes can help ensuring that the software performs the expected tasks without hidden features such as spy- or adware. It can also be used to audit the implementation of security sensitive features such as encryption (use of appropriate algorithms and key management), authorization and authentication.

The goal of this paper is to summarize knowledge and how-to material useful to decompile, alter and recompile .NET based solutions. Tools and key points to observe for detailed code reviews are out of scope for this publication.

In the first chapter we will cover different tools available to disassemble a .NET program. The second chapter will focus on the ways to compile such code while the third chapter lists settings which can be influenced via configuration parameters instead of modifying code. A dedicated hands-on example in our lab https://www.hacking-lab.com focuses on examples on how to disassemble and alter a .NET executable.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 2 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2 How To Disassemble .NET Code This section aims to list various tools allowing the disassembly of .NET based code which can be found in various forms:

ª Executables (with a console or graphical interface or designed for Windows services)

ª DLL files

ª Compiled ASP.NET web pages

2.1 Reflector (RedGate) Cost: 14 days free trial, $35 per license

Reflector is the most popular choice to disassemble .NET code backed up by a serious actor of the eco- system, . While Reflector was distributed in two flavours until February 2011 (Free and Pro), there is now only one version available.

There are several plugins available for Reflector which can be very handy, such as:

ª Methodist, to be able to instantiate assemblies and run code with IronPython in Reflector

ª Reflexil is able to replace intermediate language (IL) instructions and save the new result to a valid

ª Crack.NET allows disassembling running .NET processes. Instead of relying on an assembly saved on disk, this add-on can hook into a loaded thread. This add-on wasn't part of this evaluation.

Reflector is the only evaluated tool which allows an automatic export of the assemblies into source code. While the generated sources are usable for code reviews, the re-compilation isn't assured in all cases.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 3 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.1.1 How to disassemble code with Reflector

The assembly taken as example below is the (in)famous LOIC client [LOIC]:

ª In Reflector, open any type of supported assembly file (*.exe, *.dll or *.mcl).

ª Browse the structure of the assembly and select the interesting part to disassemble.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 4 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

ª In the Disassembler pane, click on the "Expand Types" to get the full code in this assembly.

ª You're already done! The interpreted code – in this example in C# - is available to you.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 5 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.1.2 Next steps

You can tailor Reflector further to your needs, for example with the following options:

ª In Tools - Options, choose if you prefer the disassembly to be shown in .NET Intermediate Language (IL), C#, , Delphi, MC++, Oxygene or F#

ª In Tools - Integration Options, enable the Windows Explorer Shell Integration so that you can browse a dll or an exe directly from the contextual menu in the file explorer

ª Export the whole program into its source code to open it in your preferred IDE (e.g. Visual Studio). Note that the disassembled code can be tricky to re-compile. See the upcoming section on how to re-compile disassembled code for further examples and tricks.

ª Go to the entry point of the program to analyse its execution flow

2.1.3 Troubleshooting

You get a crash of Reflector when opening the program or adding an add-on

The presence of .NET version 4 may crash some versions of Reflector or of its add-ons. To resolve this issue, edit the Reflector.exe.config file and remove any reference to version 4.0.* in the enumeration.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 6 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.2 Overview of some Reflector add-ons

2.2.1 Reflexil

Goal of the add-on

Reflexil is an assembly editor and runs as a plug-in Reflector. Reflexil is able to manipulate IL code and save the modified assemblies to disk. Reflexil also supports C#/VB.NET code injection [Reflexil]. Detailed examples on how to use Reflexil are linked in section Detailed Hands-On in Hacking-Lab.com.

Installation and Usage

ª Identify your version of Reflector. If you're running a trial or a full version of Reflector 7 or higher, you need Reflexil 1.2. Users of elderly Reflector versions (e.g. 6.6.*) need to download Reflexil 1.1.

ª Download the appropriate add-in and unzip its content

ª Open Reflector - Menu View - Add-Ins...

ª Click add - browse to the appropriate folder and select Reflexil.Reflector.dll

ª Open Reflexil and configure the appropriate target runtime depending on your current Reflector settings. If you're unsure about the version:

o Click on the assembly to alter (e.g. DotNetFatClientHacking.exe). At the bottom of the assembly list, you'll see the properties of the assembly.

o Configure Reflexil to use the same version as the current target runtime version:

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 7 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

ª Saving an assembly edited by Reflexil is possible when selecting the assembly name and choosing option "Save as…". This option can also remove the signature of the assembly if needed.

Troubleshooting

If Reflector crashes with error "Could not find a part of the path 'c:\Documents and Settings\\Local Settings\Temp\Reflexil.Persistence\index.bat'.", browse to c:\Documents and Settings\\Local Settings\Temp\ and create an empty folder called Reflexil.Persistence.

Reflector will crash when the "Replace all with code" feature is used on a .NET 4.0 assembly. This problem could not be solved and the only workaround is to get an assembly compiled with an earlier version.

If the altered assembly crashes after having saved it, ensure that Reflexil is configured for the appropriate target runtime. In our example on the right, the assembly was compiled against .NET version 4 and so needs Reflexil to be configured.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 8 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.2.2 The Methodist

Goal of the add-on

With the help of IronPython, The Methodist allows to interact with disassembled assemblies directly using the command line. As Python (and therefore IronPython) doesn't really implement the concept of public or private classes, methods and attributes, it's possible to instantiate and interact directly with private functions.

Installation

ª Download The Methodist and unzip the content

ª Open Reflector - Menu View - Add-Ins...

ª Click add - browse to the appropriate folder and select TheMethodist.dll

Example

A basic example on how to use this add-in is available in the article [UseTheMethodist]. In our example below, we want to find the ASP.NET method implementing the request validation:

ª Once the add-on is loaded, select the pre-loaded assembly System.Web

ª Press [F3] for the search panel to open and enter keyword "crosssite"

ª Double-click on the unique result and select option disassemble (see figure on the right)

ª We now see the details of class CrossSiteScriptingValidation which is flagged as being internal and which contains internal methods such as IsDangerousString.

ª Open The Methodist (Ctrl + D or Tools - The Methodist) view. A py> prompt appears

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 9 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

ª Type the following commands

o Import of the appropriate object in our context from System.Web import CrossSiteScriptingValidation

o Create an in-memory reference to this imported object xss = CrossSiteScriptingValidation

o List all the properties and methods available for this object dir(xss)

o We see our static method IsDangerousString under the name _CrossSiteScriptingValidation__IsDangerousString. We can now interactively invoke it with the following test commands xss._CrossSiteScriptingValidation__IsDangerousString("test string") (returns false)

xss._CrossSiteScriptingValidation__IsDangerousString("") (returns true)

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 10 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.3 dotPeek (JetBrains) Cost: free

While this tool isn't yet in a stable version, it's written by JetBrains which also makes ReSharper, a well- known tool for .NET developers.

At the time of the analysis, this tool was the nicest to perform code analysis but lacked other key features of Reflector, such as the full export of assemblies and the support for add-ins. Navigation through the source code was quick and efficient, especially if you're used to all keyboard shortcuts of ReSharper.

It is possible to manually disassemble a class and the tool generates a file. The decompiled code is cleaner than in Reflector and much more likely to compile (although some edits are still required).

2.3.1 Main features of dotPeek

ª Generates clean disassembled code which can be re-compiled without major changes

ª Has an efficient navigation within the disassembled code (thanks to ReSharper's shortcuts)

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 11 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

2.4 Other tools

2.4.1 Just Decompile (Telerik)

Cost: free

Supported by another well-known actor of the .NET eco-system, this new free tool is aimed to be Reflector's free successor.

At the time of the analysis, the tool had only few options and wasn't as user-friendly as dotPeek.

2.4.2 Code Reflect

Cost: free

No plugins, no Visual Studio integration, the core idea behind Code Reflect is to keep things as simple as possible.

To disassemble the code, this tool uses the same class than Reflector - .Cecil.dll - with all its limitation (e.g. unable to recompile without major edits).

Otherwise, the tool is really as it's sold: a light version of Reflector, without any further feature than disassemble code.

2.4.3 Dis#

Cost: 399 USD

This tool was not tested as part of our evaluation. Trial version is limited to the de-compilation of seven .NET assemblies.

2.4.4 Spices.Net

Cost: 699.90 USD

This tool was not tested as part of our evaluation.

2.4.5 Tools from Microsoft

Microsoft also ships its .NET development environment with some tools, such as ilasm and ildasm. These command line tools which translate code from or to Intermediate Language only were not tested as part of our evaluation.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 12 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

3 Compile .NET code This section summarizes different ways to compile .NET code. A real-world example on how to recompile disassembled code is also provided.

3.1 How to compile code using

3.1.1 Visual Studio

The easiest way to compile code is to install , which has a free version. An offline ISO for the installation is available.

There is nothing special to mention about the installation, aside the fact you will need at least 2 GB of free disk space on your root drive. A full installation of Visual Studio 2010 C# Express will take 2.4 GB and you can install VS.2010 on another drive (e.g. E:\), but several system files will still get installed in C:\ and require 2 GB.

A registration gets asked at the end of the installation. The product can be used for 30 days before requiring free registration. Don't forget to run Windows Update after the installation, as it will download VS.2010 SP1 and other hotfixes of newly installed dependencies.

Opening a disassembled project

By default, Reflector's export feature will drop all the files in My Documents\Reflector\Disassembler\\.

A Visual Studio project is created in this folder, .csproj.

3.1.2 Eclipse

While Eclipse has dedicated plugins for .NET, they haven't been tested as part of this research.

3.1.3 Via the command line

Another possibility, especially for smaller programs, is to interact via the command line directly with the appropriate compiler. The .NET framework, installed on any Windows machine, is shipped by default with a compiler for each of the following languages:

ª aspnet_compiler.exe for web pages

ª csc.exe for C#

ª jsc.exe for J#

ª vbc.exe for Visual Basic

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 13 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

The framework installs itself in C:\WINDOWS\Microsoft.NET\Framework\. 64-bits machines get a second installation in C:\WINDOWS\Microsoft.NET\Framework64\. Each installed .NET version will end into a dedicated folder. This means that an up-to-date Windows XP machine running on a 64-bits processor will have at least 8 C# compilers installed:

ª C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework64\v1.1.4322\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework64\v3.5\csc.exe

ª C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\csc.exe

Below is an extract of the available features:

C:\>C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\csc.exe /? Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Visual C# 2010 Compiler Options - OUTPUT FILES - /out: Specify output file name (default: base name of file with main class or first file) /target:exe Build a console executable (default) (Short form: /t:exe) /target:winexe Build a Windows executable (Short form: /t:winexe) /target:library Build a library (Short form: /t:library) /target:module Build a module that can be added to another assembly (Short form: /t:module) /delaysign[+|-] Delay-sign the assembly using only the public portion of the strong name key /doc: XML Documentation file to generate /keyfile: Specify a strong name key file [...]

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 14 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

3.2 How to re-compile disassembled code

3.2.1 Pre-requisites

ª Visual Studio 2010 C# Express is installed

ª Reflector is installed

ª dotPeek is installed

ª You have a .NET assembly to disassemble (e.g. LOIC)

3.2.2 Disassemble and recompile code

ª Open Reflector, open the assembly you want to disassemble (e.g. LOIC.exe) and select the export feature.

ª Start the export and ensure that no error occurred during the process.

ª Navigate to the export folder (by default %UserProfile%\My Documents\Reflector\Disassembler\) and double-click on the Visual Studio project file which was generated (.csproj or .vbproj depending on the language you choose)

ª Visual Studio starts and asks you to convert the project. Click simply Next - Next - Finish - Close.

ª Try to build the project, by either selecting the green play button or on the solution - right click - Build Solution

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 15 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

ª Several compilation errors may exist - in our example 71 errors visible in the error list. Double-click on the list items to get the faulty code.

ª Rather than fixing all these errors, the easiest is to start dotPeek and open the same assembly. For each class in error (in our example of LOIC HTTPFlooder.cs, frmMain.cs and XXPFlooder.cs), open the relevant class in dotPeek, copy the whole content and replace the relevant file in Visual Studio.

ª Try to compile again. Two compilation errors remain, which can be solved in our example by commenting out the problematic code.

ª Run the project - LOIC in our example starts without troubles

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 16 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

4 .NET Configuration Overview The aim of this section is to demystify the *.config files found either in ASP.NET solutions (web.config) or in folders (e.g. Reflector.exe.config).

.NET applications can be configured via a XML file loaded during the assembly's start-up process. Several features can be configured in these files, but some can be disabled either:

ª In code, by the developer

ª Via a complex system of configuration file hierarchy.

For example the web.config file of an ASP.NET website inherits settings from the framework specific web.config (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config) and eventually from the framework specific machine.config (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config).

4.1 Useful configuration settings

4.1.1 Redirect all the HTTP traffic of an ASP.NET website, a Web Service or a .NET fat client via a proxy

Two solutions to achieve this redirection are possible:

ª Install and run Fiddler; this solution is quick, easy and poses little troubles in regards to SSL certificates

ª Configure the relevant web.config / .exe.config file to use a proxy. This technic will be described below.

4.1.2 How to snoop HTTP traffic of a .NET fat client

ª Open (or create) the relevant configuration file (for a .NET executable named example.exe, the configuration file will be example.exe.config)

ª Add to the file a section as in the example below

Caution: there are no settings in the configuration file to allow invalid SSL certificates. Either import the root SSL certificate of the intercepting proxy into your trusted certificate store or patch the application to allow insecure HTTPS communications.

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 17 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

Other network settings can be included. More details are available in the schema reference, including attributes for defaultProxy, authenticationModules or mailSettings sections [NetworkSettings].

4.2 Other interesting settings ª Section runtime\developmentMode allows specifying whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable.

ª Various cryptography settings can be configured [CryptoSettings].

ª Developers can include application specific settings in configSections [ConfigSections] and applicationSettings [ApplicationSettings].

ª Debug features can be enabled [DebugSettings].

A full overview is available on the MSDN of Microsoft [FullConfiguration].

5 Detailed Hands-On in Hacking-Lab.com A full case featuring detailed examples of all the previous mentioned technics is available in our security lab. Access is free, register now! https://www.hacking-lab.com/caselist/7205-disassemble-net-clients-landing.html

6 Conclusion Unless protected with a dedicated obfuscation utility .NET assemblies and executables can easily be read by anyone with minimal effort. .NET clients can therefore be attacked in several ways and any security check done in the application itself can be circumvented by a motivated attacker. Intermediate Language code can either be altered or removed from the target binaries. The source code can also be exported and a recompilation based on it can be achieved with some additional effort. This paper and the associated hands-on exercise aimed to provide an example on how all these steps can be performed.

As for web solutions, the architecture of a product involving a fat .NET client requires taking into account that any data sent by the .NET client to the server is potentially unsafe and requires server-side validation. The server must therefore perform the same sanity and business checks as done on the client to enforce consistency.

7 References 7.1 Hacking-Lab Reference ª Paper and Hands on page for this topic on Hacking-Lab.com https://www.hacking-lab.com/caselist/7205-disassemble-net-clients-landing.html

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 18 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

7.2 Notes [LOIC] http://sourceforge.net/projects/loic/files/loic/loic-1.0.6/LOIC-1.0.6.35- binary.zip/download

[UseTheMethodist] http://www.simple-talk.com/dotnet/.net-tools/methodist-make-.net-reflector- come-alive-with-ironpython/

[Reflexil] Introduction taken from http://reflexil.net/

[NetworkSettings] http://msdn.microsoft.com/en-us/library/dacty7ed.aspx

[CryptoSettings] http://msdn.microsoft.com/en-us/library/3t762ffd.aspx

[ConfigSections] http://msdn.microsoft.com/en-us/library/0hyxd0xc.aspx

[ApplicationSettings] http://msdn.microsoft.com/en-us/library/ms229207.aspx

[DebugSettings] http://msdn.microsoft.com/en-us/library/76dt1k3h.aspx

[FullConfiguration] http://msdn.microsoft.com/en-us/library/1fk1t1t0.aspx

[StackOverflowOpCode] http://stackoverflow.com/questions/1785372/why-do-i-have-to-do-ldarg-0- before-calling-a-field-in-msil

[MSDNOpCode] http://msdn.microsoft.com/en- us/library/system.reflection.emit.opcodes.ldc_i4_0.aspx

[AcceptInvalidSSLCert] http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl- certificate-programmatically/

7.3 Tools ª Reflector http://reflector.red-gate.com

ª Add-on The Methodist for Reflector Source code: http://www.simple-talk.com/content/file.ashx?file=1962 Compiled version: http://www.simple-talk.com/content/file.ashx?file=1964

ª Add-on Reflexil for Reflector http://sourceforge.net/projects/reflexil/files/DOTNET%20Compiled%20Binaries/

ª dotPeek (JetBrains) http://www.jetbrains.com/decompiler/

ª Just Decompile (Telerik) http://www.telerik.com/products/decompiler.aspx

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 19 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch

ª Visual Studio 2010 Express All-in-One ISO http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express-iso

ª Fiddler http://www.fiddler2.com/fiddler2/version.asp

8 About the Author Alexandre Herzog worked from 1998 as an IT system administrator for the trading room at the Banque Cantonale Vaudoise and acted for the support of real-time applications for traders and the back office.

Between 2004 and 2007 he attended the University of Applied Sciences Western Switzerland in Sierre. During his studies in computer sciences he co-founded the start-up enterprise BananaSecurity.com together with four other students. This company is still active today under the name of KeyLemon.com.

In 2008 he accepted a position as a development consultant at the Kiwibank in New Zealand. He was employed as a security expert and was responsible for the second and third level support of the E-banking solution.

After two years down under Alexandre Herzog returned to Switzerland and has been working as an IT security analyst for Compass Security AG since August 2010.

9 About Compass Security AG Compass Security Network Computing AG is a Swiss enterprise, based in Jona SG, which specializes in security assessments in the field of information technologies. The company has been established in 1999 by Walter Sprenger and Ivan Bütler and has grown to 20 employees since then.

Meanwhile, Compass Security continuously improved and nowadays offers comprehensive services in the field of Computer- and Network-Security. Amongst others, these services cover Penetration-Tests, Web- Application-Tests, Security Reviews and Computer Forensics. Moreover, Compass Security offers several trainings in the mentioned areas.

More information at http://www.csnc.ch

Compass Security AG T +41 55 214 41 60 Werkstrasse 20 F +41 55 214 41 61 20 / 20 Postfach 2038 [email protected] CH-8645 Jona www.csnc.ch