I show you how to Crack a .NET Application (3 clicks)
Tags: csharp, dotnet, security, programming
Published: 2022-01-20 15:55:00

⚠️**Disclaimer:** _This article is for educational and training orientation, we are not responsible for the misuse of the techniques and explanations mentioned in this article and / or the use of the tools mentioned / provided, also we do not assume responsibility for the actions carried out with the information of the same. Please use this information for ethical purposes._

---

I do this article for a very simple reason, in our offices a co-working space) **there are quite a few companies that develop in .NET**, and one day at lunch I commented what we were doing and they did not understand anything, it turns out that **they had no idea what decompilation is.**

They did not know that **with a simple tool you could see, copy or modify its development** —_not in all cases you should be concerned_— but for some of them the core of the business is the development itself and obviously it did not do much grace.

**I have to say that this happens in all compiled languages, but I will focus on .NET which is what we master.**

In this article **I am going to show basic notions about de-compilation** and reverse engineering, if you are interested in something more complex, do not hesitate to ask us!


----

## What is de-compilation

De-compilation is the reverse of compilation (I'm going to patent this great explanation).

That is, the **COMPILATION** is basically:

- You write code
- You push the magic **compile** button and it becomes an executable/file/.exe/dll... (Well, it should ... surely you forgot a semicolon or something like that 😪) you will also have 103 warnings ⚠, but if you don't open your eyes, you don't see them 🤭.

The process will be something like this:

![compiling and application](https://media.giphy.com/media/uZef4xSKjC2Ig/giphy.gif)

Well, de-compilation is the opposite, you have an executable file, .dll, .exe..., and with a tool (decompiler) you get the original source code.

![decompilation](https://media.giphy.com/media/3o72F7RrTPW6jymXew/giphy.gif)

And is it simple 🙄?
I'd say it's easier than compiling, but let's see how it's done.

---

## Decompiling a .NET / .NET Core application

Let's decompile a simple application:

![decompiling .net app](https://dev-to-uploads.s3.amazonaws.com/i/53imkigur6cpxjtvhc6h.png)

For this example we will use [DnSpy](https://github.com/dnSpy/dnSpy). There are several tools and each one is good for something in particular, but DnSpy is one of the best for decompiling and debugging .NET applications.

When we compile our .NET Core application, we will obtain the compiled files, in the case of **.NET Core the ".exe" file will be the executable**, but it will be in charge of executing the **".dll" that contains the code of our application**.

Ok, let's proceed to decompile the .dll file:

![decompiling net core](https://dev-to-uploads.s3.amazonaws.com/i/pg8b9q3yg77i2kcuondn.png)

To do this, all we have to do is drag it to DnSpy:

![dnspy .net core](https://i.gyazo.com/f6f97462b428dcce96850362f22f79e7.gif)

Once loaded, the original source code will be shown and we can work on it, we can analyze it, modify it, debug it, etc.

---

### Viewing the source code

Once our application is decompiled, we can navigate through the source code as if it were our own project:

![source code .net](https://dev-to-uploads.s3.amazonaws.com/i/owqhjr292atvxicg9wgf.png)

---

### Debug the app

This will be useful to understand how it works or to obtain some values in memory.

For example, let's put a breakpoint before doing a subtraction:

![dnspy breakpoint](https://dev-to-uploads.s3.amazonaws.com/i/jjk9fvb2yevpnm4rukrj.png)

and then we will run the application:

![dnspy debug net core](https://dev-to-uploads.s3.amazonaws.com/i/9sgvoo4gwzxfootsj054.png)

Here is a simple example:

![dnspy debug](https://dev-to-uploads.s3.amazonaws.com/i/cqo6rwz4osf2rig455ev.png)

This is a function that can be very useful at times, but it can also be dangerous ⚡.

---

### Modify the code

We can modify and re-compile the application without any problem:

![craking .net core app](https://dev-to-uploads.s3.amazonaws.com/i/8vlq5rmvh4o183y12cbc.png)

*We can also do it using IL code, but if we do not know it it will be much more complex.*

We change that simple text:

![changing cil body .net core](https://dev-to-uploads.s3.amazonaws.com/i/bpjw1v97e9vj8e1uv9go.png)

and we compile again:

![compiling .net core](https://dev-to-uploads.s3.amazonaws.com/i/foyu3kdc8nkjn4zhk6im.png)

Now to save our modified application, we will give:

![saving module dnspy](https://dev-to-uploads.s3.amazonaws.com/i/9kwrhlg9535qvr6tzrxl.png)

We will select the name of the file, its path and we will mark the following options:

![metadata dnspy](https://dev-to-uploads.s3.amazonaws.com/i/0v27wu3zkv6wl0bpfjie.png)

and we will have our modified application:

![modified net core app](https://dev-to-uploads.s3.amazonaws.com/i/r08z5shihurcgxjvq2u8.png)

Ok, these are simple and unimportant examples, I leave to your imagination 💭 everything that could be done with these simple tools.

Now we are going to see other types of applications, because **compilation in .NET is the same, it does not matter if you use c#, vb, ASP, Xamarin, Blazor, everything works in the same way**, let's see then with a Blazor application.

---

## Decompiling a web application with Blazor

Now we have created a sample web application with Blazor, this is the application code in visual studio:

![blazor net core app](https://dev-to-uploads.s3.amazonaws.com/i/fmg7z04nomjljhn01keu.png)

Basically it is an application that shows the weather and we have added `Dotnetsafer` in the middle so that we can see it later in the decompiled application, here is the web application:

![blazor webapp](https://dev-to-uploads.s3.amazonaws.com/i/0tn9l7lc7j4tfl6z1f1r.png)

Ok, let's get the code again.

First we will use our browser (it does not matter which one), since when loading the .NET libraries to display the application, it makes a call to obtain them.

We must enter inspection mode `Ctrl + Shift + C` and go to section `Network`, later reload the page with `Ctrl + F5`.

Here will be the file that contains the code of our web application:

![.net blazor file](https://dev-to-uploads.s3.amazonaws.com/i/zc13mzocwwy8qzfz2gs8.png)

_You can also obtain all the dependencies or own .net files that are used by the application_

Well, we download it and open it again with DnSpy:

![decompiling blazor with DnSpy](https://dev-to-uploads.s3.amazonaws.com/i/foj06la257pk9j34ggy5.png)

Once we have the decompiled file we can do everything that I mentioned in the previous point.

---

## Decompiling a mobile app with Xamarin

We raised the level of difficulty a little 🧨, but the operation is still the same.

We have created a simple application for mobile devices with Xamarin, the compiled application will have the extension .APK

The first thing we will do is unzip the APK, there are tools for this, but it is not necessary, for something so simple we can use [winrar](https://www.winrar.es/descargas), (yes, the program that never expires 🆓):

![decompiling apk](https://dev-to-uploads.s3.amazonaws.com/i/iz87jmtxtsrbbxhj6f6u.png)

and we will copy all the files in a folder:

![decompiling xamarin apk](https://dev-to-uploads.s3.amazonaws.com/i/9a1ylqxs2jhsk3cofc7k.png)

Inside the folder `Assemblies` all .NET files will be found:

![.net xamarin files](https://dev-to-uploads.s3.amazonaws.com/i/53ndcyjpra3jqoh81tmy.png)

Here comes the interesting thing, these files have **lz4 compression**, which will give us an error if we try to decompile it with DnSpy:

![dnspy error decompiling xamarin files](https://dev-to-uploads.s3.amazonaws.com/i/bw2bujqigxlxq07133d3.png)

For this I bring a simple solution, a small Python script that will help us decompress all the .NET .dll files.

Yes, this sounds very complex, and it seems that you must be an expert:

![hacking .net](https://media.giphy.com/media/rMS1sUPhv95f2/giphy.gif)

But it really is something very simple that we will do in less than a minute.

---

### Decompress Xamarin .NET Libraries

_If you don't have Python on your machine, [install it previously](https://www.python.org/downloads/)._

Once we have Python (I run it from the [VSCode](https://code.visualstudio.com) terminal) we proceed:

### Install lz4:

![https://dev-to-uploads.s3.amazonaws.com/i/ua8pyhcf6ard0h1dx2pl.png](https://dev-to-uploads.s3.amazonaws.com/i/ua8pyhcf6ard0h1dx2pl.png)

`python -m pip install lz4` or simply `pip install lz4`

### Use of the decompression script

```python
import lz4.block
import sys
import struct
import os

def print_usage_and_exit():
    sys.exit("usage: py .\\decompressor.py target_path")

cwd = os.path.abspath(os.getcwd())

def decompress(filePath):
    input_filepath = filePath
    output_path = os.path.join("extracted", "");

    if(not os.path.exists(output_path)):
        os.mkdir(output_path)

    output_filepath = os.path.join(output_path, os.path.basename(filePath))
    header_expected_magic = b'XALZ'

    with open(input_filepath, "rb") as xalz_file:
        data = xalz_file.read()

        if data[:4] != header_expected_magic:
            sys.exit("The input file does not contain the expected magic bytes, aborting ...")

        header_index = data[4:8]
        header_uncompressed_length = struct.unpack('<I', data[8:12])[0]
        payload = data[12:]

        print("header index: %s" % header_index)
        print("compressed payload size: %s bytes" % len(payload))
        print("uncompressed length according to header: %s bytes" % header_uncompressed_length)

        decompressed = lz4.block.decompress(payload, uncompressed_size=header_uncompressed_length)

        with open(output_filepath, "wb") as output_file:
            output_file.write(decompressed)
            output_file.close()
        print("result written to file")

if __name__ == "__main__":
    n = 0
    for file in os.listdir(cwd):
        try:
            if(file.endswith(".dll")):
                decompress(file)
                n += 1;
        except:
            print("failed to decompress " + os.path.basename(file))

    print("\\nDecompressed ", n, " assemblies!")

```

*The author of this script is Christian Reitter, X41 D-Sec GmbH, thank you for your article at [X41 D-Sec GmbH](https://www.x41-dsec.de/security/news/working/research/2020/09/22/xamarin-dll-decompression/), we have modified it to unzip all the files in the directory.*

We will copy the code into a file called `decompress.py` and we will save it in the same path as our .dll files.

---

### Decompress the files we need:

![decompress .net xamarin files](https://dev-to-uploads.s3.amazonaws.com/i/z06xnl84dsztoghjpqqw.png)

We will do it with `py .\decompressor.py .\`, we'll let it decompress all the .dll files in the directory.

In this case I am only interested in the two files corresponding to my application.

What has not been so difficult?

![hacking xamarin](https://media.giphy.com/media/102h4wsmCG2s12/giphy.gif)

Now we have the files ready to open with DnSpy:

![decompiling xamarin files with dnspy](https://dev-to-uploads.s3.amazonaws.com/i/ta93uh0a1qt4in5k0tw1.png)

Now again we can do everything I mentioned earlier, the procedure is always the same, only the way in which the files are compiled varies.

This applies to all applications under .NET, such as games developed in Unity with C #, virtual reality applications and augmented reality.

Did you like this article?

It has been very simple but I consider it fine for a basic level and learn a little about these topics 😊.

If you have found it interesting, do not hesitate to support it, and tell us below 👇 if you want to know something else, like let's talk about **cracking**, **injection** and other aspects.

We could do some interesting practices or whatever you want to see around here.

Thank you for reading the article ❤ and remember that in ByteHide we will be uploading articles about security in relation to .NET 🛡.


Thank you for your attention, we hope you have learned a lot!

![goodbye](https://media.giphy.com/media/ZBVhKIDgts1eHYdT7u/giphy.gif)