Normal view

There are new articles available, click to refresh the page.
Before yesterdayB4rtik

Execute assembly via Meterpreter session - Part 2

6 October 2019 at 00:00

Recently I push some updates to the project after an exchange of ideas on the possibility of creating a PR towards the Metasploit master branch.

The most significant are:

Module

Added the ability to inject HostingCLR into an existing process via the PID parameter Added the ability to specify the process to be created instead of notepad.exe Added parameter to enable / disable Amsi bypass Refactoring of the code to comply with Metasploit best practices

DLL

Added functionality to detect the CLR necessary for the assembly in order to load the correct one, thus also supporting .Net 3.5 assemblies. Added verification of the CLR already loaded in the process, if already loaded a new one is not instantiated. Amsi Bypass using AmsiScanBuffer patching technique.

In the first part I focused more on the ruby ​​code because the implementation of the HostingCLR dll was almost the same as presented by Etor Madiv in his original project. In this second part we will instead focus on improving the dll in order to be feasible for a PR on the Metasploit main branch.

How to find witch CLR version is needed

To be able to load the correct CLR version we need to know witch version the assembly requires. Furthermore, the verification must be able to be performed on a byte array.

The first thing that comes up in mind is to see if it is possible to find a signature inside the byte array to determine the version. A Windows executable, EXE or DLL, must conform to a file format called PE. A standard Windows PE file is divided into sections:

  1. MS-DOS header
  2. PE header
  3. optional header
  4. Native Image Section (.data, .rdata, .rsrc, .text)

These are the standard sections of a typical Windows executable. The C/C++ compiler allows you to add your custom sections to the PE file using a #pragma compiler directive.

What about the CLR? Metadata and IL code find space in an extension of the COFF/PE format.

The CLR data part contains metadata and IL code, both determine how the program will be executed. Compilers for the CLR must issue both the CLR header and the data information in the generated PE file, otherwise the resulting PE file will not be executed in the CLR. The CLR header holds a number of relevant details required by the runtime, like Runtime, MetaData directory and Entry point token.

MS Docs

So now we know that it is possible to extract the version. Opening a .Net assembly with HxD we can see how the version changes by rebuilding with different Target Frameworks and determining signatures for the search.

.Net 4.0

.Net 3.5

CLR v4.0.30319 - 76 34 2E 30 2E 33 30 33 31 39 CLR v2.0.50727 - 76 32 2E 30 2E 35 30 37 32 37

Load CLR only if needed

Another interesting idea is the possibility to load the CLR only if necessary.

For example we could think of using for the PROCESS powershell.exe parameter that we know to be a .Net process or to locate the pid of a .Net process, and go to load the assembly directly using the CLR already available.

This can be easily done by going to enumerate the runtimes loaded through EnumerateLoadedRuntime

If the required runtime is already loaded, use it without creating a new one.

Amsi bypass

Starting from the version of the Framework 4.8 Anti Malware Scan Interface is also integrated into the CLR, this means that the Assembly.Load call is subject to scanning by Amsi.

For the Amsi bypass I opted for AmsiScanBuffer Patching tencique.

Introducing RedPeanut

26 August 2019 at 00:00
__________________________________________________________________________
ooooooo________________oo_ooooooo___________________________________oo____
oo____oo___ooooo___oooooo_oo____oo__ooooo___ooooo__oo_ooo__oo____o__oo____
oo____oo__oo____o_oo___oo_oo____oo_oo____o_oo___oo_ooo___o_oo____o_oooo___
ooooooo___ooooooo_oo___oo_oooooo___ooooooo_oo___oo_oo____o_oo____o__oo____
oo____oo__oo______oo___oo_oo_______oo______oo___oo_oo____o_ooo___o__oo__o_
oo_____oo__ooooo___oooooo_oo________ooooo___oooo_o_oo____o_oo_ooo____ooo__
__________________________________________________________________________
________________________________________________RedPeanut_v0.3.0___@b4rtik
__________________________________________________________________________

Currently being tested.


RedPeanut is a small RAT developed in .Net Core 2 and its agent in .Net 3.5 / 4.0. RedPeanut code execution is based on shellcode generated with DonutCS. It is therefore a hybrid, although developed in .Net it does not rely solely on the Assembly.Load. This increases the detection surface, but allows us to practice and experiment with various evasion techniques related to the dotnet environment, process management and injection. This behavior can be changed at rutime with the "managed" and "unmanaged" commands. If you are interested in a .Net C2 Framework that is consistent and can be used in an enagement, I suggest Covenant.

RedPeanut is weaponized with:

  • GhostPack
  • SharpGPOAbuse
  • SharpCOM
  • EvilClippy
  • DotNetToJS
  • SharpWeb
  • Modified version of PsExec
  • SharpSploit
  • TikiTorch

RedPeanut Agent

The RedPeanut agent can be compiled in .Net 3.5 and 4.0 and has pivoting capabilities via NamedPipe. The agent, when executed in an unmanaged mode, performs its own critical tasks in a separate process to prevent the AV response to detection or error during execution make you lose the whole agent.

The execution flow is as follow:

  1. Process creation
  2. Inject static shellcode generated with DonutCS
  3. The loader loads and executes the stager or module

The agent currently only supports https channel.

C2 Channel

The agent checkin protocol is very simple:

  1. The stager requires an agent id, the message is encrypted with RC4 with the shared serverkey
  2. The server decrypt the message, compile and sends the agent, generate and send KEY and IV for future communications AES encryption, the message is encrypted RC4
  3. The stager decrypt the message and load the agent via Assembly.Load
  4. The agent sends a checkin message to the server, the message is encrypted with AES

Alternatively, the covered channel feature can be activated(at the moment it is just a PoC). The idea is to imitate the web traffic carried out by a real user. Usually a web page is composed of the html page and all the objects necessary for its display as css, images, etc. At the request of a new task the answer from the server will not be directly the encrypted task but an html page from which to extract the link to the image that will have embedded the encrypted task. The http request for the image will contain the Referer header.

Content delivery

Content delivery is organized in 4 channels:

  1. C2 Channe customizable via profile
  2. Dynamic content generated/managed by RedPeanut customizable via profile
  3. Static content mapped to /file/
  4. Covered channel for the recovery of the image containing the payload mapped to /images/

Profiles

RedPeanut capability of customization of network footprint both server side and client side. The properties that can be set are:

  • General
    • Delay (between requests)
    • ContentUri (url of dynamic content eg. dll hta etc.)
    • UserAgent
    • Spawn (the process to create to perform critical tasks)
    • HtmlCovered (Enable covered channel)
    • TargetClass (Class to search for image recover)
  • Http Get
    • ApiPath (comma separated list of url es /news-list.jsp,/antani.php etc.)
    • Server
      • Prepend
      • Append
      • Headers (name and value pair for http headers)
    • Client
      • Headers    
  • Http Post
    • ApiPath (comma separated list of url es /news-list.jsp,/antani.php etc.)
    • Param (the name of the post request payload parameter)
    • Mask (format for interpreting the key value pair eg {0}={1}) (need more work...)
    • Server
      • Prepend
      • Append
      • Headers (name and value pair for http headers)
    • Client
      • Headers

Domain Fronting

To enable the domain fronting support it is necessary to value the "Host" header in the client section, both post and get (exemplified in the default profile 2)

PowerShellExecuter

The PowerShellExecuter module allows you to execute oneliner commands or files in a runspace with AMSI bypass, Logging bypass and PowerView already loaded.

Launchers

  • Exe
  • Dll
  • PowerShell
  • Hta (vbs,powershell)
  • InstallUtil
  • MSBuild
  • MacroVba

Local modules

  • EvilClippy

Agent Tasks

  • Upload
  • DownLoad
  • SharpWeb
  • SharpWmi
  • SharpUp
  • UACBypass Token Duplication
  • SharpDPAPIVaults
  • SharpDPAPITriage
  • SharpDPAPIRdg
  • SharpDPAPIMasterKeys
  • SharpDPAPIMachineVaults
  • SharpDPAPIMachineTriage
  • SharpDPAPIMachineMasterKeys
  • SharpDPAPIMachineCredentials
  • SharpDPAPICredentials
  • SharpDPAPIBackupKey
  • Seatbelt
  • SafetyKatz
  • RubeusTriage
  • RubeusTgtDeleg
  • RubeusS4U
  • RubeusRenew
  • RubeusPurge
  • RubeusPtt
  • RubeusMonitor
  • RubeusKlist
  • RubeusKerberoast
  • RubeusHash
  • RubeusHarvest
  • RubeusDump
  • RubeusDescribe
  • RubeusCreateNetOnly
  • RubeusChangePw
  • RubeusASREPRoast
  • RubeusAskTgt
  • SharpCOM
  • SharpGPOAddUserRights
  • SharpGPOAddStartupScript
  • SharpGPOAddLocalAdmin
  • SharpGPOAddImmediateTask
  • PowerShellExecuter
  • LatteralMSBuild
  • SharpPsExec
  • SharpAdidnsdump
  • PPIDAgent
  • SpawnAsAgent
  • SpawnShellcode
  • SpawnAsShellcode
  • SharpMiniDump

Persistence

  • Autorun
  • Startup
  • WMI
  • CRL

BlockDlls

Starting with version 0.3.0 RedPeanutAgent supports the blockdlls command. With this option enabled, child processes that are created to perform tasks in unmanaged mode are created with the attribute PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON. This attribute prevents the process of loading dlls that are not signed by Microsoft, this could protect our tasks from AV and EDR hooking techniques. Credits for using this process creation mitigationpolicy goes to @xpn

Direct Sysstem Call and Dynamic Dll Loading

RedPeanutAgent uses Dynamic Dll loading to avoiding using of suspicious Dll Imports. Credits for Dynamic Dll Loading goes to @TheRealWover, @cobbr_io and @FuzzySec for their work in SharpSploit.

Some AV and EDR vendors used hooking technique to keep track of activities. To avoid using hooked syscall RedPeanutAgent uses direct syscall, auto injecting the necessary code. Credits for Direct Syscall goes to @Cneelis

Running

To run RedPeanut you need to have dotnet installed. To install dotnet on Kali:

wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.asc.gpg
mv microsoft.asc.gpg /etc/apt/trusted.gpg.d/
wget -q https://packages.microsoft.com/config/debian/9/prod.list
mv prod.list /etc/apt/sources.list.d/microsoft-prod.list
chown root:root /etc/apt/trusted.gpg.d/microsoft.asc.gpg
chown root:root /etc/apt/sources.list.d/microsoft-prod.list

apt-get install apt-transport-https
apt-get update
apt-get install dotnet-sdk-2.1
git clone --recursive https://github.com/b4rtik/RedPeanut.git

For the covered channel functionality it is necessary to install the libgdiplus library, therefore:

For linux users:

apt-get install -y libgdiplus

For OSx

brew install mono-libgdiplus

Assembly signing key generation

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>sn.exe -k 4096 key.snk

Than copy key.snk in Workspace/KeyFile

root@kali:~# cd RedPanut
root@kali:~/RedPeanut# dotnet run
Using launch settings from /root/Projects/RedPeanut/Properties/launchSettings.json...
Enter password to encrypt serverkey: 

__________________________________________________________________________
ooooooo________________oo_ooooooo___________________________________oo____
oo____oo___ooooo___oooooo_oo____oo__ooooo___ooooo__oo_ooo__oo____o__oo____
oo____oo__oo____o_oo___oo_oo____oo_oo____o_oo___oo_ooo___o_oo____o_oooo___
ooooooo___ooooooo_oo___oo_oooooo___ooooooo_oo___oo_oo____o_oo____o__oo____
oo____oo__oo______oo___oo_oo_______oo______oo___oo_oo____o_ooo___o__oo__o_
oo_____oo__ooooo___oooooo_oo________ooooo___oooo_o_oo____o_oo_ooo____ooo__
__________________________________________________________________________
________________________________________________RedPeanut_v0.3.0___@b4rtik
__________________________________________________________________________

[*] No profile avalilable, creating new one...
[RP] >

Shellcode generator

DonutCS is a shellcode generation tool that creates position-independant shellcode payloads from .NET Assemblies. This shellcode may be used to inject the Assembly into arbitrary Windows processes. Given an arbitrary .NET Assembly, parameters, and an entry point (such as Program.Main), it produces position-independent shellcode that loads it from memory. The .NET Assembly can either be staged from a URL or stageless by being embedded directly in the shellcode.

CLR Persistence

The CLR persistence technique was presented for the first time in this post by @Am0nsec. The technique consists in carrying out the application domain manager hooking. As described in the post, the assembly to carry out hooking is necessary which is available in the GAC. An assembly to be used from the GAC must be strong-named and then signed with a key. The CLR persistence module needs a key to be able to sign the assemblies, which can be generated with the sn.exe tool as follows:

**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.3
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>sn.exe -k 4096 key.snk

Copy the key.snk file to Workspace/KeyFile folder. This file will be used to sign the assembly for persistence.

Tools updating

Some of the well-known tools present in RedPeanut such as the GhostPack tools are wrapped in full and executed on the client side. To update the tools, for example SeatBelt, without updating the entire repository is necessary: Clone the Seatbelt repository, rename the "Main" method in "Execute", insert the public modifier and recompile as dll. The dll must be compressed and encoded in Base64 with the ps RastaMouse's script Get-CompressedShellcode.ps1

Credits

Execute assembly via Meterpreter session

27 December 2018 at 00:00

Backgroud

Windows to run a PE file relies on reading the header. The PE header describes how it should be loaded in memory, which dependencies has and where is the entry point. And what about .Net Assembly? The entry point is somewhere in the IL code. Direct execution of the assembly using the entry points in the intermediate code would cause an error. This is because the intermediate code should not be executed first but the runtime will load the intermediate code and execute it.

Hosting CLR

In previous versions of Windows, execution is passed to an entry point where the boot code is located. The startup code, is a native code and uses an unmanaged CLR API to start the .NET runtime within the current process and launch the real program that is the IL code. This could be a good strategy to achieve the result. The final aim is: to run the assemply directly in memory, then the dll must have the assembly some where in memory, any command line parameters and a reference to the memory area that contains them.

Execute Assembly

So I need to create a post-exploitation module that performs the following steps:

  1. Spawn a process to host CLR (meterpreter)
  2. Reflectively Load HostCLR dll (meterpreter)
  3. Copy the assembly into the spawned process memory area (meterpreter)
  4. Copy the parameters into the spawned process memory area (meterpreter)
  5. Read assembly and parameters (dll)
  6. Execute the assembly (dll)

To start the Host process, metasploit provides Process.execute which has the following signature:

Process.execute (path, arguments = nil, opts = nil)

The interesting part is the ops parameter:

  • Hidden
  • Channelized
  • Suspended
  • InMemory

By setting Channelized to true, I can read the assembly output for free with the call

notepad_process.channel.read

Once the Host process is created, Metasploit provides some functions for interacting with the memory of a remote process:

  • inject_dll_into_process
  • memory.allocate
  • memory.write

The inject_dll_into_process function copies binary passed as an argument to a read-write-exec memory area and returns its address and an offset of the dll's entry point.

exploit_mem, offset = inject_dll_into_process (process, library_path)

The memory.allocate function allocates memory by setting the required protection mode. In this case I will write the parameters and the assembly in the allocated memory area, for none of these two elements I need the memory to be executable so I will set RW.

I decided to organize the memory area dedicated to parameters and assemblies as follows:

  • 1024 bytes for the parameters
  • 1M for the assembly

assembly_mem = process.memory.allocate (1025024, PAGE_READWRITE)

The third method allows to write data to a specified memory address.

process.memory.write (assembly_mem, params + File.read (exe_path))

Now I have the memory address of dll, the offset to the entry point, the memory address fo both the parameters and the assembly to be executed. Considering the function

Thread.create (entry, parameter = nil, suspended = false)

I can use the memory address of dll plus the offset as a value for the entry parameter and the address the parameter and assembly memory area as the parameter parameter value.

process.thread.create (exploit_mem + offset, assembly_mem)

This results in a call to the entry point and an LPVOID pointer as input parameter.

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)

It's all I need to recover the parameters to be passed to the assembly and the assembly itself.

ReadProcessMemory(GetCurrentProcess(), lpPayload, allData, RAW_ASSEMBLY_LENGTH + RAW_AGRS_LENGTH, &readed);

About the assemblies to be executed, it is important to note that the signature of the Main method must match with the parameters that have been set in the module, for example:

  • If the property ARGUMENTS is set to "antani sblinda destra" the main method should be "static void main (string [] args)"
  • If the property ARGUMENTS is set to "" the main method should be "static void main ()"

Chaining with SharpGen

A few days ago I read a blog post from @cobb_io where he presented an interesting tool for inline compilation of .net assemblies. By default execute-assembly module looks for assemblies in $(metasploit-framework-home)/data/execute-assembly but it is also possible to change this behavior by setting the property ASSEMBLYPATH for example by pointing it to the SharpGen Output folder in this way I can compile the assemblies and execute them directly with the module.

Source code

❌
❌