Windows is still the most popular end-user operating system and security products are mostly installed on Windows operating systems. Desktop operating system market share graph is given below from NetMarketShare report for August 2017. If an operating system has the highest usage rate in end user systems, it will be the target of attackers in the same way. This means security products will be used in that operating systems and that security products will have to develop themselves day by day against attacks.

Desktop/Laptop Operating System Browsing Statistics

Since Windows is the most commonly used operating system, the target systems usually have Windows operating system in the penetration tests. If you intend to infiltrate the Windows operating system, Meterpreter is usually used as RAT in penetration tests because there is full integration with Metasploit. Also my favorite RAT is the Meterpreter. :) Although the Meterpreter has great features, it can be used for illegal purposes, not just for legal purposes, it means, Meterpreter can classified as malicious by security products. This leads to the necessity of bypassing the security products in the target system in penetration tests. OK, we know what we need; “We want to use the Meterpreter and bypass the security countermeasures taken at target”. So how the security products work and how will the SpookFlare help us?

We can evaluate the operations of the security countermeasures implemented in the operating systems with three stages. The first is signature-based detection, the second is behavioral detection and the third is reputation-based detection. The first thing that is accepted in the literature to bypass the signature-based detection is obfuscation, so you can bypass countermeasures taken. The second, you must change the behavior of malware to bypass behavioral detection. So if you have been detected using Mimikatz to get the hashes of the local users in the target system, you can use the procdump tool of SysInternals. You can bypass behavioral detection because procdump is signed by the authority and generally it used for legal purposes. The last thing is reputation-based detectionand there are some things that are getting complicated at this point. Because the perspectives of security products may be different. Sometimes the properties of your application can be defined as malicious by some security products and the reputation-based detections algorithms changes completely from security product to security product. At this point, your experience is fully engaged in order to bypass the security product. At the end of the day, security products can detect and prevent the attack vectors if they “know”. I mean if you have unknown technique or way you can bypass the countermeasures of target system.

There are multiple ways the bypass security products. SpookFlare has a different perspective to bypass security measures and it gives you the opportunity to bypass the endpoint countermeasures at the client-side detection and network-side detection. SpookFlare is a loader generator for Meterpreter Reverse HTTP and HTTPS stages. SpookFlare has custom encrypter with string obfuscation and run-time code compilation features so you can bypass the countermeasures of the target systems like a boss until they “learn” the technique and behavior of SpookFlare payloads.

You can find the technical details of SpookFlare following headings and the payload execution steps following graph.

Execution Steps of SpookFlare Payload

Obfuscation

In software development, obfuscation is the deliberate act of creating source or machine code that is difficult for humans to understand. SpookFlare uses the obfuscation for the string names. Therefore, it will be difficult to develop a signature in a certain “string(s)”. Actually writing a signature for certain string is a behavior done by many malware-analysts or security product developers. When a malware analyst analyzes the sample or by dynamic analysis systems then, once it is determined to be a malware, a proper signature of the file is extracted and added to the signatures database of the AV or Endpoint Security product. The signature of the file will change if you change any byte in a file. If you change the correct bytes, you can bypass the signature-based detections. SpookFlare uses the string obfuscation. Therefore, each generated payload will be unique as possible.

Runtime Code Compiling

Even though the application is built using obfuscation, the code must be completely changed after a point and this point is when your payloads are detected as malicious because string-based obfuscation can achieve success in a certain extent. For example, if the string-based obfuscation is used in your payload also the OpenProcess, VirtualAlloc etc. system calls are used in your payload, there is a possibility of your payload detect by security products. That system calls are suspicious because so many malware use that system calls. To escape from these and other situations, SpookFlare compiles the actual code during runtime. Thus, the definition of suspicious defines like system calls is hidden. Like the system calls, the actual code hiding is explained under the ongoing heading.

The .NET Framework includes a mechanism called the Code Document Object Model (CodeDOM) that enables developers of programs that emit source code to generate source code in multiple programming languages at run time, based on a single model that represents the code to render. Sometimes developers need it, and .NET Framework makes it possible. For example, the following C # code compiles the C # code assigned to the “code” variable during execution and runs it.

using System;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace compileTest {
    class Program {
        static void Main() {
            string code = @"
    using System;

    namespace runtimeCode {

        public class compile {

            public static void Main() {
                Console.WriteLine(""Hello from runtime compiled code!"");
                Console.ReadKey();
            }

        }

    }";
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = true;
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
            if (results.Errors.HasErrors) {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors) {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
            Assembly assembly = results.CompiledAssembly;
            Type program = assembly.GetType("runtimeCode.compile");
            MethodInfo main = program.GetMethod("Main");
            main.Invoke(null, null);
        }
    }
}

SpookFlare payloads are uses the runtime code compiling and execution. Each generated SpookFlare payloads contains own loader code and when executed, it give the loader code to the compiler.

Source Code Encryption

So far we have learned that we can use the string-based obfuscation and compile the code at runtime. However, when doing all of this we need to hide code the actual loader. Because the loader code being moved will have a disadvantage against signature-based fixes when the loader code defined clear-text. So SpookFlare encrypts the original loader’s code using the RijnDaelManaged class and when executed it decrypts the loader code after then it give the code to the compiler. It is act like crypters and finally, it execute the compiled code.

Bypassing Network Level Countermeasures

I inspired this section from @Arno0x0x and wanted to improve it. We usually use Meterpreter Staged Payloads, as you know, these payloads download their cores (stage) over the network and run in the target system memory. Security countermeasures may not only be in the end-user system but also at the network level, remember the IDS/IPS etc. Although the security countermeasures in end-user systems are bypassed, security countermeasures at network level can jeopardize an entire operation.

So, how can they detect the malicious files at the right network level? The answer is signature-based detection. For this situation you can use an encoder for Meterpreter’s core (stage) and you can bypass the network-level countermeasures. It can be the first conceivable idea and makes sense. If you use an encoder, you need to add a stub to decode it and creation of a signature for decoder is easier for malware analysts. We need something different and more difficult to analyze or detect. SpookFlare can handle this better without any encoder.

How do malware analysts write signatures for a binary? By creating unique patterns and creating these patterns for the head of the file. I mean, malware analysts are creating signatures for the header part of the file. Thus, they can prevent false-positives and detect malicious files more easily. So here is the solution or SpookFlare offer; if we add random bytes at the beginning of the application we can bypass network-based countermeasures and for this solution we need to patch Metasploit.

Detection Result of Network-Based Countermeasures for Meterpreter

The file meterpreter_loader.rb in Metasploit is responsible for creating the Stage. The /usr/share/metasploit-framework/lib/msf/core/payload/windows/x64/meterpreter_loader.rb file for x64 stages and /usr/share/metasploit-framework/lib/msf/core/payload/windows/meterpreter_loader.rb file for x86 stages. We will add random bytes to the beginning of the Stage and for this process and we can use securerandom library in the Ruby language. The screenshot of this process is given below.

Patching Metasploit

After, we define the creation of the actual Stage with generated random bytes. The screenshot of this process is given below.

Patching Metasploit

Finally we will tell the Loader to remove the bytes added from the beginning of Stage and run the rest. Array.Copy or Buffer.BlockCopy functions can be used in C# for this, but Array.Copy is used in the SpookFlare Loaders because Array.Copy is faster than the Buffer.BlockCopy.

The scan results of SpookFlare loader, standard and patched Meterpreter stages are given below.

SpookFlare Loader Scan Result SpookFlare Loader Scan Result

Standart Meterpreter Stage Scan Result Standart Meterpreter Stage Scan Result

Patched Meterpreter Stage Scan Result Patched Meterpreter Stage Scan Result

Conclusion

As you know the security product firms can generate unique signatures of SpookFlare or behavioral algorithms when the usage rate of SpookFlare increases. When this happens, it will be time to change signatures and behavior. I/We will change signatures and behavior, or I/We will develop entirely new techniques. At the end of the day we will bypass the measures again in a very high probability because this is a cat mouse game that has no end. :) I developed the SpookFlare and technique for use in penetration tests, red team engagements and it is purely educational. Please use with responsibility.

In the above sections, I tried to explain as much as possible how SpookFlare works. You can access the usage video and the project on Github below links.

Usage Video, https://www.youtube.com/watch?v=p_eKKVoEl0o
Project, https://github.com/hlldz/SpookFlare

References