Tag Archive for: landscape

A Native Application Subsystem Backdoor

A Native Application Subsystem Backdoor

What is a Native Application?

Most Windows applications come in two “flavors”, GUI and console (command-line) applications. There are a few differences between the two, most notably the Windows Subsystem on top of which they are executed. The Subsystem can be seen by examining an executable’s PE header:

There are actually quite a few Subsystem options, but today we are going to be focusing our interest in the Native subsystem. Native Applications are PEs compiled to run against the Native Windows subsystem. Unlike the other two Subsystems you might already be familiar with, the Native one is quite bare-bones.

First of all, attempting to execute a Native Application through File Explorer (by double-clicking) or the command line yields the following error:

Our only option for executing Native Applications (aside from manually loading the binary in memory) is RtlCreateUserProcess.

Secondly, Native Applications can only depend on ntdll.lib, the static version of ntdll.dll. This is quite an important limitation, since there is also no possibility of dynamically importing libraries. Essentially, we have to stick to NTDLL exports. This happens because applications targeting the Native subsystem are generally expected to be executed early on in the userland bootstrap sequence, where other subsystems might not have been (fully) initialized.

Why develop a Native Application?

An interesting, but relatively undocumented execution mechanism in Windows resides in smss.exe, the Windows Session Manager. Session Manager, among other things, provides the functionality of auto-starting applications during the initialization of the user session. An example of an intended use case is filesystem verification, which happens by having smss.exe spawn autochk.exe during the “Welcome” logon screen.

This mechanism utilizes the following registry hive:

Notice the BootExecute multi-string entry which reads:

autocheck autochk *

This is the entry which triggers autochk.exe and passes it the argument “*”, the command that smss.exe executes at the “Welcome” screen. Notice how only the executable name is mentioned, not the extension or the full path. This is because in order for a Native Application to be executed by smss.exe through BootExecute, it needs to be located in C:\Windows\System32.

The information outlined here can also be found in this blog post by Protexity. Digging a little deeper though, I uncovered some interesting insights on the inner workings of smss.exe, the BootExecute key as well as a new registry entry that functions similar to BootExecute, the BootExecuteNoPnpSync key.

Why target smss.exe?

Native Applications executed by smss.exe through BootExecute do so under the context of NT Authority\SYSTEM, with a plethora of granted privileges and very early in the usermode initialization, before the userland components of EDR solutions are initialized. As a result, there are quite a few offensive opportunities to this implementation, provided that we have:

  • a way to remotely edit the HKLM registry hive of a host
  • a way to plant a binary to \??\C:\Windows\System32 on the target host.

From an offensive-security standpoint, it was decided to focus on opening process and thread handles using the NT Authority\SYSTEM process token as a POC.

Evitan – The Native Application backdoor

Building Native Applications with Visual Studio requires a couple of configuration steps. Stack cookies have to be disabled (/GS-) and intrinsics are a good idea (/Oi). As far as linking is concerned, the Native Application must be linked ONLY against ntdll.lib and the Subsystem has to be set to Native.

Finally, the Native Application does not begin its execution at int main(), but rather at void NTAPI NtProcessStartup(PPEB peb).

After writing a quick hello-world Native Application to test and verify the project skeleton, I decided on this main loop for the backdoor:

  • Begin execution
  • Create a synchronization event
  • Allocate some shared memory for communication
  • Wait until the event is set by the client process
  • Read the shared memory to identify the client process ID and command
  • Get a handle to the client process
  • Execute the commands and duplicate any resulting handles to the client process
  • Go to step 4

I then borrowed Pavel’s implementation of NativeRun and incorporated it into the project, to allow testing Native Applications without going through smss.exe.

Fleshing out the above main loop looks a bit like the following:

On the client side, an application that requests elevation from the backdoor looks like this:

Too good to be true…

The issue

Although through NativeRun both the backdoor and the client operated as expected, when spawned through smss.exe the backdoor resulted in hanging the “Welcome” screen. This was an immediate road block, since another limitation was added to the list; Native Apps executed through BootExecute need to terminate their execution for smss.exe to continue its operations. Or… Do they really?

I decided to break out Ghidra and start looking around at the inner workings of smss.exe. During its setup stages it reads the BootExecute key, along with other relevant information from the registry and then proceeds to call SmpExecuteCommand for each member in the SmpBootExecuteList:

SmpExecuteCommand calls SmpParseCommandLine and then passes the result to SmpExecuteImage:

SmpExecuteImage is responsible for executing a Native Application and holds the root cause of our issue, a WaitForSingleObject call that expects our process to terminate:

Luckily enough, our problem lies within a branch, controlled by some flags:

By reversing SmpParseCommandLine we find more information on the supported flags. As it turns out, the following flags are supported:

  • BOOTEXECUTE_ASYNC
  • BOOTEXECUTE_SECURE
  • BOOTEXECUTE_DEBUG
  • BOOTEXECUTE_AUTOCHECK

They are set by comparing the first token of each command (remember the syntax?) to some predefined values which are:

  • async (Executes a Native Application without waiting for it to terminate)
  • secure
  • debug (The execution attempt is logged but the application is not actually spawned)
  • autocheck (Bingo, our magic string!)

The data references look as follows:

And finally…

Proof of Concept

After a quick modification of the BootExecute key, dropping the backdoor to \??\C:\Windows\System32\Evitan.exe and a quick reboot,

we can execute EvitanClient.exe, the POC client application that will request elevated actions, in this case terminating a system process:

The complete project files accompanying this blog post can be found at the HackCraft Github.

Why not use token impersonation?

When Evitan was initially fleshed out, its goal was taking advantage of SE_DEBUG_PRIVILEGE and SE_TCB_PRIVILEGE to open a handle to the backdoor client process, receive a target thread handle and duplicate the handle to its own process using the acquired backdoor client process thread handle. Soon after it would duplicate its process token the same way and set it to the impersonation token for the targeted thread. The problem with this approach is that duplicating token handles across session boundaries is unsupported and as a result, the idea of transferring privileges through the token was dropped in favor of transferring privileged resources by handle duplication.

Features

The final version of Evitan shared along with this blog post contains the following list of features:

  • Elevated Process / Thread Termination
  • Token Session ID Swapping
  • Process Memory Dumping

More features/commands can be added easily, as required.

Disclaimer

This blog post and the accompanying project files are provided only as a POC and are not expected to be production-grade, bug-free code. Please take this into consideration before utilizing Evitan.

References

Defending Against the Surge: Red Teaming in the Wake of Ransomware Attacks in Europe and Greece

As we bid farewell to 2023, let us highlight some enlightening insights.  The research conducted by Corvus Insurance has shown a significant increase of over 95% in ransomware attacks compared to the previous year. According to Statista, over 72% of businesses worldwide were affected by ransomware attacks during 2023. Education, local and state government, healthcare, distribution and transport were among the top targets.

Moreover, Statista mentions that 36% of the organizations suffered ransomware attacks because of exploited vulnerabilities in 2023, with leisure and entertainment industry to be the most vulnerable to ransomware attacks. Credential compromise was the second-most common cause of successful ransomware attacks, while malicious e-mail ranked third. Consequently, 51% of organizations are planning to increase security investments as a result of a breach, including incident response planning and testing, employee training, threat detection and response tools, as IBM points out.

Source: Corvus Insurance 

Significant Ransomware attacks in Headlines

The International Battleground

In recent years, we have witnessed a surge in ransomware attacks targeting organizations across all sectors. From disrupting critical infrastructure to paralyzing healthcare systems, these attacks have not only caused financial losses but have also shaken the foundations of trust in our digital systems and in several organizations.

To start with one of the most far-reaching cyber-attacks of the year, the file-transferring software MOVEit was victim to a ransomware attack starting in May 2023, unknown SQL injection vulnerability (CVE-2023-34362) in the MOVEit Transfer software which led to the attack affecting hundreds of billion-dollar companies including the BBC, Zellis, British Airways, Ofcom, Ernst and Young, Transport for London and more. In April, financial services firm, NCR, was hit by a ransomware attack that disrupted payment processing systems. Last but not least, in November China’s biggest lender, ICBC, U.S. arm, was a ransomware victim.

Greece’s Wake-Up Call

Beyond Europe, ransomware has cast its dark shadow across Greece. Major corporations, government agencies and even critical infrastructure have fallen prey to sophisticated attacks. The ripple effects have been felt not only in financial terms but also in terms of the broader implications for national security and public trust.

To mention some noteworthy ransomware attacks, Papaki.gr, the well-known Greek domain registrar, reported on July 27th that their systems had been accessed without authorization. While the details of the cyber-attack have not been disclosed, Papaki has informed that it is likely that two clients were affected by data leak. Moreover, Hellenic Public Properties Company (HPPC) experienced such an attack last November with limited impact on the organization’s service operations as backups were properly configured and regularly updated. Also in November, the University of the Aegean had important documents published into the dark web after refusing to pay the ransom to attackers.

Hackcraft: A Proactive Αrtful Defense Strategy

In the face of this escalating threat landscape, organizations must adopt a proactive stance in defending against ransomware attacks. Neurosoft’s powerful service is Hackcraft, a Red Team highly capable of delivering exceptional Adversary Simulation services (Red Teaming). Red Teaming involves an adversary attack simulation of real-world threats (Advanced Persistent Threats) based on realistic scenarios that evaluate the overall security posture in order to test and measure the effectiveness and responsiveness of the people, processes and technology used to defend an organization digitally and physically.

Understanding Ransomware Simulation Exercises

To empower organizations towards this ransomware surge Hackcraft members have designed Ransomware Simulation Exercises. These exercises simulate real-life attack scenarios to test the organizations’ ransomware prevention and detection capabilities. Based on threat intelligence, these Exercises are tailored to meet the specific needs and objectives of each organization, providing a comprehensive and customized solution to the unique challenges faced by different business sectors.

Benefits of Hackcraft Ransomware Simulation

  • Realistic Scenario Testing
    Hackcraft Red Team creates tailor-made ransomware attacks based on real-life ransomware samples such as Cl0p and Lockbit. These ethical attacks help organizations better prepare and understand their team’s response to the pressure of an actual ransomware attack.
  • Identifying Vulnerabilities
    Hackcraft Ransomware Simulation allows organizations to evaluate the overall ransomware readiness, security posture and anti-ransomware controls. Identifying vulnerabilities and weaknesses in their current cybersecurity measures against ransomware threats helps in addressing potential gaps in security.
  • Testing Incident Response Plans
    During a Ransomware Simulation, Hackcraft can help organizations assess the readiness of their incident response plans. This includes evaluating communication processes, decision-making, coordination among various teams, security controls, and in-place mechanisms, processes and policies.
  • Employee Training and Awareness
    Hackcraft Ransomware Simulations offer a chance to train employees in identifying and responding to ransomware threats, raising awareness and improving overall security hygiene.
  • Meeting Compliance Requirements
    In some industries conducting regular Red Team Exercises, including Ransomware Simulation Exercises, is a requirement for compliance. It helps organizations demonstrate their commitment to cybersecurity best practices.
  • Strategic Decision-Making
    Insights gained from Hackcraft Ransomware Simulation debriefing enable informed strategic decision-making regarding cybersecurity investments and improvements. It supports a culture of continuous improvement, ensuring that defenses evolve to address emerging threats.

Hackcraft Ransomware Simulation vs Ransomware

The recent ransomware incidents that occurred in Greece and Europe should be a wake-up call for organizations to prioritize proactive cybersecurity measures. One such effective strategy is to adopt Ransomware Simulation, which allows organizations to foresee, detect and prevent potential threats before they escalate into crippling attacks. As we forge ahead, Hackcraft views Ransomware Simulation not merely as a security measure, but as a readiness evaluation against the known and the unknown of the ransomware threat landscape. It is a weapon of choice for safeguarding our digital future against the rising tide of ransomware.

Introducing Blueprint

Intro

As discussed in our previous post, regarding Fairplay, during Red Team engagements a lot of focus is shifted into preserving and protecting the malware. Fairplay does its fair share of work to provide us with the information on when we get detected, but before that, we needed a way to make sure that each and every single payload that we utilize is unique. This ultimately prevents mass-actions taken against static information in our payloads, since each payload is always unique statically and perhaps even sometimes behaviourally.

However, not all payloads are the same. Red Teams usually assess and evaluate multiple potential entrypoints, each one with its own caveats. There are vast differences between platforms, technological stacks and contexts. There are for example native Windows executables, managed .NET assemblies, VBScript/JScript HTA or CHM enabled documents, etc. The plethora of possible combinations of attack chains and scenarios is huge when the potential options are served with a multitude of different attack chains, comprised of sets of TTPs. The previous example now becomes:

  • Native Windows Service Executable that performs self injection of shellcode using RtlRunOnceExecuteOnce
  • .NET executable that performs AppDomainManager hijack to remote process shellcode injection targetting Explorer.exe

As one can observe, the list quickly grows out of hand rather quickly. This created a nuance from both the developers’ as well as the operators’ perspectives. It became apparent that producing unique builds that are comprised of smaller, TTP based modules, in multiple “wrapper” formats (.exe, .dll, .hta, etc.) at will without deep diving in the code required for an across the board solution that could template malware at source code level.

What is Blueprint?

Blueprint is a python3 source-code level modular templating solution based on Jinja. It is developed by the Hackcraft Red Team and is open-source and freely available.

Github repository: https://github.com/Hackcraft-Labs/Blueprint

Jinja boilerplate

Blueprint extends the classic Jinja syntax and offers modularity through the use of filters. Filters, functionality native to Jinja, are essentially python-backed functions that receive input which they operate on and return the output. They can be called in the Jinja context in the form of pipelines, which are evaluated to the final outputs. An example is as follows:

{{ "Example" | filter1 | filter2 }}

Here, the expression inside the double braces will be evaluated as the equivalent of the following python snippet:

filter2(filter1("Example"))

Example definitions of filter1 and filter2 could be as follows:

def filter1(inp):
    return inp + "1"

def filter2(inp):
    return inp + "2"

As a result the above expression would be evaluated to Example12.

Blueprint modules

Blueprint offers an extensive list of sinister modules which we use extensively in our malware, which of course can be extended in python3 and is as follows:

  • Input/Output
    • Content : Retrieves the binary contents of a file
    • Output : Writes to a binary file
  • Crypto
    • AES : Performs AES encryption with a randomly generated key and IV
    • XOR : Performs XOR encryption with a randomly generated single-byte key
  • Hashing
    • DJB2 : Computes the DJB2 hash of the input, which is useful when hashing known strings for obfuscation
  • Format
    • HexArr : Formats the input to a comma-separated array of hex represented bytes
    • DecArr : Formats the input to a comma-separated array of decimal represented bytes

The author of the template can use these modules as a language-agnostic build-time metaprogramming environment to tweak certain aspects of the code. Consider for example the following use case:

// File: example.h.tpl

// In this malware, we need to execute a piece of shellcode.
// The shellcode is AES encrypted at rest and decrypted before being self-injected at runtime.

// Let us define a C array of bytes to hold the AES encryption key.
// Notice the Blueprint templating which will evaluate to the value of the variable AES_KEY as a hex-array.
unsigned char key[] = { {{ AES_KEY | hexarr }}} ;

// Same process, but for the encryption IV this time.
unsigned char iv[] = { {{ AES_IV | hexarr } }}

// Now for the actual shellcode, let us:
// - Retrieve the contents of payload.bin 
// - Encrypt it with the aes module (Random key and IV will be generated and output to AES_KEY and AES_IV respectively)
// - Represent it as a hex-array
unsigned char payload = { {{ "payload.bin" | content | aes | hexarr }} }

Notice how this is not constrained to a certain compiler, let alone a specific language or context. This can be used in any source code file and can of course be extended at will.

Behavioral modularity

In Blueprint templates, we can also leverage Jinja control-flow primitives to offer a way to the operator to toggle certain features on or off at build time, without having to make changes to the code. Consider the following example:

// File: example.c.tpl

// Include our payload header file, produced by example.h.tpl
#include "example.h"

// ... snip ...
int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hInstPrev, PSTR cmdline, int cmdshow)
{
    // Decrypt the shellcode
    perform_aes_decryption(payload, sizeof(payload), key, iv);

    // If PATCH_ETW is set, then disable it.
    {% if PATCH_ETW %}
        disable_etw();
    {% endif %}

    // Perform the injection.
    inject(payload, sizeof(payload));
}

Metaprogramming concepts

Another cool side-effect of templating is that you can provide an abstract interface to the operations team. Consider for example the use case where malware can target a list of processes to inject shellcode to, which can vary in size. Also, all these strings should be encrypted in some way to prevent static identification. This becomes as simple as:

{% for process_name in INJECT_TO_PROCESSES %}
unsigned char proc_{{ loop.index }}_str[] = { {{ process_name | xor | hexarr }} };
{% endfor %}

We just defined a number of C arrays containing the XOR encrypted versions of the process name strings defined in the python array INJECT_TO_PROCESSES.

Bringing it all together

Now all that’s left is wrapping up this hot mess of features into a neat little present before presenting the dev team’s work to the operators, which is offered through the magic of JSON configuration files. An example for our case would be as follows:

{
    "filters":[
        "crypto.AES",
        "crypto.XOR",
        "io.Content"
    ],
    "targets":[
        {
            "input":"example.h.tpl",
            "output":"example.h",
            "variables":{}
        },
        {
            "input":"example.c.tpl",
            "output":"example.c",
            "variables":{
                "INJECT_TO_PROCESSES":["explorer.exe", "TextInputHost.exe"],
                "PATCH_ETW":true
            }
        }
    ]
}

This configuration file can be editted at will by the operations team to provide malleable capabilities to each campaign and scenario, while allowing for it to morph on its own as well during each built, to provide OPSEC against static checks. It is parsed by Blueprint, in the following way:

  • The filters defined are imported into the context.
  • For each entry in targets:
    • The input file is evaluated as a Blueprint template.
    • The variables are inserted into the context.
    • The end result is written to the file defined in the output.

Then, your usual build pipeline continues, targetting the files output by Blueprint. Again, this supports anything from an VS/MSBuild C/C++ project to a JScript CHM Help Studio project.

That’s it, we are done! Almost

A love letter to the devs

Blueprint abstracts away many of the nitty gritty details of the underlying malware code, but after using it for a while it was pretty aparrent that it completely broke syntax highlighting on every editor out there. Unfortunatelly, the solution to this can not be easily abstracted away, but we have created a small plugin for Visual Studio Code to facilitate authoring Blueprint malware templates, which supports syntax highlighting for Blueprint templates containing the following languages/contexts:

  • C/C++
  • C#
  • Batch

The list can of course be further extended. May the eye-strain be reduced! 🙂

The plugin will be released in the near future, so keep an eye out!

Contributions

Contributions to the code base of Blueprint are very much welcome through Pull Requests submitted on its repository, both for the framework as well as for new modules that provide functionality related to malware development.

Establishing Fairplay in Red Team engagements

Intro

During Red Team engagements, one of the most important tasks is to protect the crown jewels of the operation. As soon as the payloads prepared by the Red Team are delivered to the targets, security analysts of the Blue Teams submit potential malware samples to multiple online sources for further analysis. This is also common practice in multiple automated security solutions, such as email gateways, Antiviruses, sandbox frameworks and EDR products.

Many of these online sources can be queried using a file hash to identify whether a sample was previously analysed, as well as retrieve the results of such analysis. Also, most of them offer web-based APIs, that allow for the automation of such tasks.

Github repository: https://github.com/Hackcraft-Labs/Fairplay

Fairplay is an extensible modular framework that was developed by the Hackcraft Red Team, which aims to alleviate part of the heavy lifting of monitoring file hashes across multiple online-based sources, as well as provide an extensible way to generate notifications across multiple platforms.

When provided a list of file hashes to monitor, Fairplay will silently query its list of online sources, and provide notifications for when a sample is encountered (thus submitted for analysis) the first time, as well as for any submissions that follow on new sources, letting the Red Team know when their payload is analysed.

Possessing this information allows the Red Team to modify their attack paths, TTPs and overall strategy on the fly, according to analysis actions made by engineers or automated solutions. Since it was developed with extensibility in mind, and has been of help to the Red Team on multiple occasions, we decided to release it as open-source software.

Information regarding installing and configuring the tool can be found in its repository, along with a template configuration file in which API keys and webhook URLs can be specified. Examples of monitored IOCs are also provided.

Integrations

Fairplay currently supports monitoring of submissions on the following platforms, utilizing their web API:

  • VirusTotal
  • HybridAnalysis
  • Google Search
  • MetaDefender
  • MalwareBazaar

Moreover, it supports generating notifications on the following services, using their webhooks:

  • Microsoft Teams
  • Slack

It also supports notifying directly to the console window.

Extensibility

Fairplay and its modules are developed in Python3. Instructions regarding the creation of new collectors (modules that query info in online sources) and notifiers (modules that generate notifications) can be found in Fairplay’s repository and there is also support for retrieving “extra” information that are potentially provided by online sources, such as the detection type of the sample, how many engines detected is as malicious or clean, etc. “Hot” reloading of plugins and monitored IOCs is also supported, from its command-line interface.

Reported Information

The following image is an example of a Microsoft Teams notification generated by Fairplay. In this example, the file hash of the popular antivirus test file ‘EICAR’ was identified for the first time on HybridAnalysis, for which Fairplay reports the detection type and provides a link to the submitted file for further observation.

Contributions

Contributions to the code base of Fairplay are very much welcome through Pull Requests submitted on its repository, both for the framework as well as for new modules that either collect information from a new online source or generate notifications on a new channel.

Tag Archive for: landscape