Skip links

How to …?

Cyber Risk Assessment

A Step-By-Step Guide to Cyber Risk Assessment

A Step-By-Step Guide to Cyber Risk Assessment A cyber risk assessment is a process of identifying, analyzing, and evaluating the cyber threats and vulnerabilities that could affect your organization’s assets, operations, and reputation. A cyber risk assessment can help you prioritize your security efforts, comply with regulations, and communicate with stakeholders. There are different approaches […]

Incident Response

Incident Response Evolution and Current Challenges Part 1

Incident Response Evolution and Current Challenges

Incident Response (IR) is the approach used to manage security incidents in order to reduce the damage to an organization and improve the recovery of affected services or functionalities. IR activities follow a plan, which is the set of directions that outline the response procedures and the roles of different team members. IR has become a necessity for organizations facing rising threat levels, and this chapter discusses its importance.

With the focus of this article being the evolution and then the challenges of IR, we’ll begin by looking at how IR has evolved with threats and advancements in technology. We’ll then look at the challenges that IR teams face today, especially with the tasks of assessing current levels of security in the organization, anticipating and protecting systems from future threats, being involved in legal processes relating to cyber-attacks, uniting the organization during crises, and integrating all security initiatives. We’ll cover the following main topics:

  • The evolution of incident response
  • Challenges facing incident response
  • Why do we need incident response?

We’ll begin by exploring some recent history, and how IR has evolved over time.

The cybersecurity threat landscape

With the prevalence of 24-hour connectivity and modern advancements in technology, threats are evolving rapidly to exploit different aspects of these technologies. Any device is vulnerable to attack, and with the Internet of Things (IoT) this became a reality. The IoT has seen increased usage of digital communication and the increased transfer of data via digital platforms increases the risk of data interception by malicious individuals. Pervasive surveillance through digital devices is also a recent threat with the increased use of smartphones. Governments can now engage in digital surveillance of their citizenry with the excuse of providing security against potential terrorist threats. Criminals can also do similar tasks to the detriment of the targeted victims. In 2014, ESET, an internet security company, reported 73,000 unprotected security cameras with default passwords.

Understanding the attack surface

In very simple terms, the attack surface is the collection of all potential vulnerabilities that, if exploited, can allow unauthorized access to the system, data, or network. These vulnerabilities are often also called attack vectors, and they can span from software to hardware, to a network, and to users (which is the human factor). The risk of being attacked or compromised is directly proportional to the extent of attack surface exposure. The higher the number of attack vectors, the larger the attack surface, and the higher the risk of compromise.

Just to give you the extent of an attack surface and its exposure, let’s look into MITRE’s Common Vulnerabilities and Exposures (CVE) database, here: https://cve.mitre.org/cve/. The database provides a list of cybersecurity vulnerabilities that have been targeted in the past, to make organizations aware of them should they use the same software or hardware systems. It has 108,915 CVE entries at the time of writing, which have been identified over the past few decades. Certainly, many of these have been fixed, but some may still exist. This huge number indicates how big the risk of exposure is.

Any software that is running on a system can potentially be exploited using vulnerabilities in the software, either remotely or locally. This applies particularly to software that is web-facing, as it is more exposed, and the attack surface is much larger. Often, these vulnerable applications and software can lead to the compromise of the entire network, posing a risk to the data it is managing. Furthermore, there is another risk that these applications or software are often exposed to: insider threat, where any authenticated user can gain access to data that is unprotected due to badly implemented access controls.

An attack surface may be exposed to network attacks that can be categorized as either passive or active, depending on the nature of the attack. These can force network services to collapse, making services temporarily unavailable, allow unauthorized access to the data flowing through the network, and other negative business impacts.

In the event of a passive attack, the network might be monitored by the adversary to capture passwords, or to capture sensitive information. During a passive attack, an attacker can leverage the network traffic to intercept communications between sensitive systems and steal information. This can be done without the user even knowing about it. Alternatively, during an active attack, the adversary will try to bypass the protection systems using malware or other forms of network-based vulnerabilities to break into the network assets; active attacks can lead to the exposure of data and sensitive files. Active attacks can also lead to Denial-of-Service (DoS) type attacks. Some common types of attack vectors are:

  • Social engineering scams
  • Drive-by downloads
  • Malicious URLs and scripts
  • Browser-based attacks
  • Attacks on the supply chain (which are becoming increasingly common)
  • Network-based attack vectors

Verizon data breach report

To find out more about this topic, I would highly recommend that you download and read Verizon data breach reports: https://enterprise.verizon.com/resources/reports/dbir/.

According to the Verizon breach report, hackers’ tactics and motives have not changed much over the last 5 years, with 63% of breaches launched for financial gain, and 52% of breaches featuring hacking. Ransomware attacks account for nearly 24% of attacks involving malware, and breaches continue to take a long time to be detected, with 56% taking several months or longer to be discovered. And typically, by the time the breach has been discovered, the damage has already been done.

The Verizon data breach report should catch your attention in three areas. Knowledge of these areas will help you to build a better IR plan, which we will cover later in this book:

1, Misconfigurations are the fastest-growing risk that you need to address
2. Vulnerabilities are more often than not patched too slowly, leading to breaches
3. Attacks against web applications are now the fastest-growing category

To combat the many threats facing an organization’s attack surface, modern IT security defense should be a layered system: a single-layer approach to security is simply not enough anymore. In the event of a network breach, the victim individual or organization can sustain huge damage, including financial and operational implications, and loss of trust. In the recent past, the number of breaches has increased for various reasons. The attack vectors for these breaches could be many, such as viruses, Trojans, custom malware for targeted attacks, zero-day-based attacks, or even insider threats.

With every passing day, the network of connected devices is increasing, and, while this growth of connectivity continues to grow bigger, the risk of exposure is also increasing. Furthermore, it is no longer dependent on how big or small businesses are. In today’s cyberspace, it is hard to establish whether any network or application is prone to attacks, but it has become extremely important to have a sustainable, dependable, and efficient network system, as well as applications. Properly configured systems and applications will help reduce the risk of attack, but we might not ever be able to eliminate the risk of attack completely. However, this book will attempt to relay insight into the world of cybersecurity, highlight the dangers that digital networks and technology pose to individuals and companies, and provide guidelines on how to better prepare for such threats.

Now, having established the cybersecurity landscape and the relevance of the attack surface, let’s move on to a key element of this book: what is incident response?

What follows is a relevant excerpt, which indicates the various factors that shape an organization’s attack surface:

The evolution of incident response

The general notion regarding the origin of hacking is that it started in the 1960s, around the time of the invention of modern computers and operating systems. To disprove this notion, let’s next briefly explore the history of data breaches, to develop an idea of the context behind the modern attack environment.

The history of data breaches

Data interception associated with hacking activities goes as far back as 1836, when two persons were caught intercepting data transmissions in a criminal manner.

During the last decade of the 1700s, France implemented a national data network, which was one of a kind at the time, to transfer data between Paris and Bordeaux. It was built on top of a mechanical telegraph system, which was a network of physical towers. Each tower was equipped with a unique system of movable arms. The tower operators would use different combinations of these arms to form numbers and characters that could be read from a similar distant tower using a telescope. This combination of numbers and characters was relayed from tower to tower until it reached the other city. As a result, the government achieved a much more efficient, speedier mechanism of transferring data.

Interestingly, all this happened in the open. Even though the combinations were encrypted and would’ve required an experienced telegraph operator to decode the message at the far end to bring up the original message, the risks were just around the corner. This operation was observed by two bankers, Francois and Joseph Blanc. They used to trade government bonds at the exchange in Bordeaux, and it was they who figured out a method to poison the data transfer and obtain an indicator of current market status, by bribing the telegraph operators. Usually, it took several days before the information related to bond performance reached Bordeaux by mail. Now, they had an advantage to get that same information well before the exchange in Bordeaux received it.

In a normal transmission, the operator included a backspace symbol to indicate to the other operator that they needed to avoid the previous character and consider it a mistake. The bankers paid one of the operators to include a deliberate mistake with a predefined character, to indicate the previous day’s exchange performance, so that they could assume the market movement and plan to buy or sell bonds. This additional character did not affect the original message sent by the government, because it was indicated to be ignored by the receiving telegraph operator. But this extra character would be observed by another former telegraph operator who was paid by the bankers to decode it by observing through a telescope.

Using this unique information related to market movement, the Blanc brothers had an advantage over the market for two years, until they were caught in 1836. The modern equivalent of this attack would perhaps be data poisoning, a man-in-the middle attack, misuse of a network, or social engineering. However, the striking similarity is that these attacks often go unnoticed for days or years before they get caught. Unfortunately, the Blanc brothers could not be convicted as there were no laws under which they could be prosecuted at that time. Maybe the Blanc brothers’ hack was not so innovative compared to today’s cyber-attacks, but it does indicate that data has always been at risk. And, with the digitization of data in all shapes and forms, operations, and transport mechanisms (networks), the attack surface is huge now. It is now the responsibility of the organization and individuals to keep the data, network, and computer infrastructure safe.

Let’s fast-forward another 150 years, to 1988. This is when the world witnessed the first-ever computer virus—the Morris worm. Even though the creator of the worm, Robert Tappan Morris, denied the allegation that it was intended to cause harm to computers, it did, indeed, affect millions of them. With the intention of measuring the vastness of the cyber world, Morris wrote an experimental program that was self-replicating and hopped from one computer to another on its own.

It was injected into the internet by Morris, but, to his surprise, this so-called worm spread at a much faster rate than he would have imagined. Within the next 24 hours, at least 10% of internet-connected machines were affected. This was then targeted to the Advanced Research Projects Agency Network (ARPANET), and some reports suggested that the number of connected computers at the time was around 60,000. The worm exploited a flaw in the Unix email program Sendmail, and a bug in the finger daemon (fingerd). Morris’ worm infected many sites, including universities, military organizations, and other research facilities. It took a team of programmers from various US universities working non-stop for hours to reach a solution. It took a few more days still to get back to a normal state. A few years later, in 1990, Morris was convicted by the court for violating the Computer Fraud and Abuse Act; unlike at the time of the Blanc brothers, when there was no law to prosecute, Morris was criminally liable.

Moving forward another two decades to 2010, when the world saw what it never imagined could happen in Stuxnet: an extremely coordinated effort to create a specifically crafted piece of software, which was purpose-built to target the Iranian nuclear facility. It targeted Industrial Control Systems (ICSes). This was designed only to target a specific brand and make of Siemens ICS, which manages the speed of centrifuges in a nuclear facility. It is presumed that it was designed to deliver onsite because the Iranian facility that it was targeting was air-gapped.

This was one-of-a-kind industrial cyber sabotage. The malware was purpose-built so that it would never leave the facility of the nuclear plant. However, somehow (there is still speculation as to how), it still made its way out to the internet. It took researchers many months after its discovery to figure out the working principle of the malware. It’s speculated that it took at least a few years to develop it to a fully functional working model. Since Stuxnet, we have witnessed many similar attack patterns in the form of Duqu and Flame, and it’s believed by some experts in this field that malware similar to these are still active.

Currently, we are seeing new variants of attack with new modus operandi. Their intent is to earn money by using ransomware or to steal data in order to sell or destroy it. Ransomware attackers use computer viruses to infect a computer, encrypting and locking information in the computer. They then ask for a ransom from the owners to regain access to their computers. Alternatively, attackers might use victims’ infrastructure to run crypto miner malware to mine cryptocurrencies.

Today, security has taken center stage, not only because the attack surface has increased for each entity, or the number of successful high-profile and mass attacks is more normalized, but because of the fact that each one of us knows that the need to secure data is paramount, irrespective of whether you are a target or not.

To read the rest please go to Article 2, here

Article 2 will cover

  • Modern cybersecurity evolution

  • Challenges facing incident response

  • Protecting the company brand

  • Preventing future breaches

  • Preparing for attacks

  • Developing cyber resilience

Read this article on Packt Web site,

Click here to read Incident Response related articles

Incident Response in the Age of Cloud

Anyone can be hacked. It is just a matter of time. Even the right technology, e.g. the best firewall or anti-virus application, can fall short of protecting your system against cyber-attacks since cybercriminals are always in search of new methods and ways to infiltrate into systems. Responding to an incident quickly will help an organization to minimize its losses, decrease vulnerabilities, rebuild services and processes. Therefore, at this very moment, it is significant to know the best practices to respond to a successful cyber-attack.

Organizations should have skilled employees and sophisticated tools to identify the threats or to respond to and eliminate them. Without knowing the best practices of an incident response process, the organization will be an easy target for cybercriminals and be vulnerable to a cyber-attack.

This book will be a guideline for organizations on how to address and manage the aftermath of a cyber-attack, and how to control the cybersecurity breach in a way that decreases damage, recovery time and costs.

Cybercriminals are always in search of new methods to infiltrate systems. Quickly responding to an incident will help organizations minimize losses, decrease vulnerabilities, and rebuild services and processes.

In the wake of the COVID-19 pandemic, with most organizations gravitating towards remote working and cloud computing, this book uses frameworks such as MITRE ATT&CK® and the SANS IR model to assess security risks.

The book begins by introducing you to the cybersecurity landscape and explaining why IR matters. You will understand the evolution of IR, current challenges, key metrics, and the composition of an IR team, along with an array of methods and tools used in an effective IR process. You will then learn how to apply these strategies, with discussions on incident alerting, handling, investigation, recovery, and reporting.

Further, you will cover governing IR on multiple platforms and sharing cyber threat intelligence and the procedures involved in IR in the cloud. Finally, the book concludes with an “Ask the Experts” chapter wherein industry experts have provided their perspective on diverse topics in the IR sphere.

Incident Response in the Age of Cloud
Incident Response in the Age of Cloud by Dr Erdal Ozkaya

By the end of this book, you should become proficient at building and applying IR strategies pre-emptively and confidently.

Cybercriminals are always in search of new methods to infiltrate systems. Quickly responding to an incident will help organizations minimize losses, decrease vulnerabilities, and rebuild services and processes.

In the wake of the COVID-19 pandemic, with most organizations gravitating towards remote working and cloud computing, this book uses frameworks such as MITRE ATT&CK® and the SANS IR model to assess security risks.

The book begins by introducing you to the cybersecurity landscape and explaining why IR matters. You will understand the evolution of IR, current challenges, key metrics, and the composition of an IR team, along with an array of methods and tools used in an effective IR process. You will then learn how to apply these strategies, with discussions on incident alerting, handling, investigation, recovery, and reporting.

Further, you will cover governing IR on multiple platforms and sharing cyber threat intelligence and the procedures involved in IR in the cloud. Finally, the book concludes with an “Ask the Experts” chapter wherein industry experts have provided their perspective on diverse topics in the IR sphere.

By the end of this book, you should become proficient at building and applying IR strategies pre-emptively and confidently.

The experts who have contributed in the book, See the full list here

To buy the book

Amazon – click here

Packt – click here

Incident Response Evolution and Current Challenges Part 1
Incident Response Evolution and Current Challenges Part 1

 

Continue reading Incident Response Evolution and Current Challenges Part 1

TedX Turkey Talk

Hacklenmemek İçin Hacklemeyi Bilmek – TedX 2023 Talk – Free Video

Hacklenmemek İçin Hacklemeyi Bilmek Hacklenmemek için hacklemeyi bilmek ne kadar doğru ?  Hacklemeyi bilmek, sizi daha tehlikeli hale getirebilir mi? . Bir hacker, bir bilgisayar sistemine veya bir ağ sistemine sızmak için kullanabilecek bir dizi araç ve teknik bilir. Bu araçlar ve teknikler, kötü amaçlı yazılım dağıtmak, hassas verileri çalmak veya sistemleri bozmak için kullanılabilir. […]

Network Security

DIFFERENCES BETWEEN EDR AND SIEM?

DIFFERENCES BETWEEN EDR AND SIEM? Nowadays, cybercriminals use sophisticated and complex strategies to infiltrate a network. That is the reason why cyberattack cases have been on the rise over the past few years. COVID-19 is not helping either, as 43% of workers have made mistakes that had security repercussions. Because of this problem, there is […]

MANAGED DETECTION RESPONSE

WHAT IS MANAGED DETECTION AND RESPONSE?

WHAT IS MANAGED DETECTION AND RESPONSE? Organizations — no matter how big or small — are finding it harder to fight cybersecurity threats today than a few years ago. A recent Enterprise Strategy Group (ESG) survey revealed that 63% of organizations claimed that it is harder to analyze threats today than it was 2 years […]

Evading

Evading industry leading endpoint protection in 2022

Evading industry leading endpoint protection in 2022

This post will cover a Blueprint for evading EDR’s , a post written by Van Mieghem on his blog. All credit is going to him, and I wanted You to be aware of this awesome post .

A blueprint for evading industry leading endpoint protection in 2022

About two years ago I quit being a full-time red team operator. However, it still is a field of expertise that stays very close to my heart. A few weeks ago, I was looking for a new side project and decided to pick up an old red teaming hobby of mine: bypassing/evading endpoint protection solutions.

In this post, I’d like to lay out a collection of techniques that together can be used to bypassed industry leading enterprise endpoint protection solutions. This is purely for educational purposes for (ethical) red teamers and alike, so I’ve decided not to publicly release the source code.

The aim for this post is to be accessible to a wide audience in the security industry, but not to drill down to the nitty gritty details of every technique. Instead, I will refer to writeups of others that deep dive better than I can.

In adversary simulations, a key challenge in the “initial access” phase is bypassing the detection and response capabilities (EDR) on enterprise endpoints. Commercial command and control frameworks provide unmodifiable shellcode and binaries to the red team operator that are heavily signatured by the endpoint protection industry and in order to execute that implant, the signatures (both static and behavioural) of that shellcode need to be obfuscated.

In this post, I will cover the following techniques, with the ultimate goal of executing malicious shellcode, also known as a (shellcode) loader:

1. Shellcode encryption

Let’s start with a basic but important topic, static shellcode obfuscation. In my loader, I leverage a XOR or RC4 encryption algorithm, because it is easy to implement and doesn’t leave a lot of external indicators of encryption activities performed by the loader.

AES encryption to obfuscate static signatures of the shellcode leaves traces in the import address table of the binary, which increase suspicion. I’ve had Windows Defender specifically trigger on AES decryption functions (e.g. CryptDecryptCryptHashDataCryptDeriveKey etc.) in earlier versions of this loader.

Evading industry leading endpoint protection in 2022

Output of dumpbin /imports, an easy giveaway of only AES decryption functions being used in the binary.

2. Reducing entropy

Many AV/EDR solutions consider binary entropy in their assessment of an unknown binary. Since we’re encrypting the shellcode, the entropy of our binary is rather high, which is a clear indicator of obfuscated parts of code in the binary.

There are several ways of reducing the entropy of our binary, two simple ones that work are:

  1. Adding low entropy resources to the binary, such as (low entropy) images.
  2. Adding strings, such as the English dictionary or some of "strings C:\Program Files\Google\Chrome\Application\100.0.4896.88\chrome.dll" output.

A more elegant solution would be to design and implement an algorithm that would obfuscate (encode/encrypt) the shellcode into English words (low entropy). That would kill two birds with one stone.

3. Escaping the (local) AV sandbox

Many EDR solutions will run the binary in a local sandbox for a few seconds to inspect its behaviour. To avoid compromising on the end user experience, they cannot afford to inspect the binary for longer than a few seconds (I’ve seen Avast taking up to 30 seconds in the past, but that was an exception).

We can abuse this limitation by delaying the execution of our shellcode. Simply calculating a large prime number is my personal favourite. You can go a bit further and deterministically calculate a prime number and use that number as (a part of) the key to your encrypted shellcode.

4. Import table obfuscation

You want to avoid suspicious Windows API (WINAPI) from ending up in our IAT (import address table). This table consists of an overview of all the Windows APIs that your binary imports from other system libraries. A list of suspicious (oftentimes therefore inspected by EDR solutions) APIs can be found here.

Typically, these are VirtualAllocVirtualProtectWriteProcessMemoryCreateRemoteThreadSetThreadContext etc. Running dumpbin /exports <binary.exe> will list all the imports. For the most part, we’ll use Direct System calls to bypass both EDR hooks (refer to section 7) of suspicious WINAPI calls, but for less suspicious API calls this method works just fine.

We add the function signature of the WINAPI call, get the address of the WINAPI in ntdll.dll and then create a function pointer to that address:

typedef BOOL (WINAPI * pVirtualProtect)(LPVOID lpAddress, SIZE_T dwSize, DWORD  flNewProtect, PDWORD lpflOldProtect);
pVirtualProtect fnVirtualProtect;

unsigned char sVirtualProtect[] = { 'V','i','r','t','u','a','l','P','r','o','t','e','c','t', 0x0 };
unsigned char sKernel32[] = { 'k','e','r','n','e','l','3','2','.','d','l','l', 0x0 };

fnVirtualProtect = (pVirtualProtect) GetProcAddress(GetModuleHandle((LPCSTR) sKernel32), (LPCSTR)sVirtualProtect);
// call VirtualProtect
fnVirtualProtect(address, dwSize, PAGE_READWRITE, &oldProt);

Obfuscating strings using a character array cuts the string up in smaller pieces making them more difficult to extract from a binary.

The call will still be to an ntdll.dll WINAPI, and will not bypass any hooks in WINAPIs in ntdll.dll, but is purely to remove suspicious functions from the IAT.

5. Disabling Event Tracing for Windows (ETW)

Many EDR solutions leverage Event Tracing for Windows (ETW) extensively, in particular Microsoft Defender for Endpoint (formerly known as Microsoft ATP). ETW allows for extensive instrumentation and tracing of a process’ functionality and WINAPI calls.

ETW has components in the kernel, mainly to register callbacks for system calls and other kernel operations, but also consists of a userland component that is part of ntdll.dll (ETW deep dive and attack vectors). Since ntdll.dll is a DLL loaded into the process of our binary, we have full control over this DLL and therefore the ETW functionality. There are quite a few different bypasses for ETW in userspace, but the most common one is patching the function EtwEventWrite which is called to write/log ETW events. We fetch its address in ntdll.dll, and replace its first instructions with instructions to return 0 (SUCCESS).

void disableETW(void) {
	// return 0
	unsigned char patch[] = { 0x48, 0x33, 0xc0, 0xc3};     // xor rax, rax; ret
	
	ULONG oldprotect = 0;
	size_t size = sizeof(patch);
	
	HANDLE hCurrentProc = GetCurrentProcess();
	
	unsigned char sEtwEventWrite[] = { 'E','t','w','E','v','e','n','t','W','r','i','t','e', 0x0 };
	
	void *pEventWrite = GetProcAddress(GetModuleHandle((LPCSTR) sNtdll), (LPCSTR) sEtwEventWrite);
	
	NtProtectVirtualMemory(hCurrentProc, &pEventWrite, (PSIZE_T) &size, PAGE_READWRITE, &oldprotect);
	
	memcpy(pEventWrite, patch, size / sizeof(patch[0]));
	
	NtProtectVirtualMemory(hCurrentProc, &pEventWrite, (PSIZE_T) &size, oldprotect, &oldprotect);
	FlushInstructionCache(hCurrentProc, pEventWrite, size);
	
}

I’ve found the above method to still work on the two tested EDRs, but this is a noisy ETW patch.

6. Evading common malicious API call patterns

Most behavioural detection is ultimately based on detecting malicious patterns. One of these patters is the order of specific WINAPI calls in a short timeframe. The suspicious WINAPI calls briefly mentioned in section 4 are typically used to execute shellcode and therefore heavily monitored.

However, these calls are also used for benign activity (the VirtualAllocWriteProcessCreateThread pattern in combination with a memory allocation and write of ~250KB of shellcode) and so the challenge for EDR solutions is to distinguish benign from malicious calls. Filip Olszak wrote a great blog post leveraging delays and smaller chunks of allocating and writing memory to blend in with benign WINAPI call behaviour. In short, his method adjusts the following behaviour of a typical shellcode loader:

  1. Instead of allocating one large chuck of memory and directly write the ~250KB implant shellcode into that memory, allocate small contiguous chunks of e.g. <64KB memory and mark them as NO_ACCESS. Then write the shellcode in a similar chunk size to the allocated memory pages.
  2. Introduce delays between every of the above mentioned operations. This will increase the time required to execute the shellcode, but will also make the consecutive execution pattern stand out much less.

One catch with this technique is to make sure you find a memory location that can fit your entire shellcode in consecutive memory pages. Filip’s DripLoader implements this concept.

The loader I’ve built does not inject the shellcode into another process but instead starts the shellcode in a thread in its own process space using NtCreateThread. An unknown process (our binary will de facto have low prevalence) into other processes (typically a Windows native ones) is suspicious activity that stands out (recommended read “Fork&Run – you’re history”).

It is much easier to blend into the noise of benign thread executions and memory operations within a process when we run the shellcode within a thread in the loader’s process space. The downside however is that any crashing post-exploitation modules will also crash the process of the loader and therefore the implant. Persistence techniques as well as running stable and reliable BOFs can help to overcome this downside.

7. Direct system calls and evading “mark of the syscall”

The loader leverages direct system calls for bypassing any hooks put in ntdll.dll by the EDRs. I want to avoid going into too much detail on how direct syscalls work, since it’s not the purpose of this post and a lot of great posts have been written about it (e.g. Outflank).

In short, a direct syscall is a WINAPI call directly to the kernel system call equivalent. Instead of calling the ntdll.dll VirtualAlloc we call its kernel equivalent NtAlocateVirtualMemory defined in the Windows kernel. This is great because we’re bypassing any EDR hooks used to monitor calls to (in this example) VirtualAlloc defined in ntdll.dll.

In order to call a system call directly, we fetch the syscall ID of the system call we want to call from ntdll.dll, use the function signature to push the correct order and types of function arguments to the stack, and call the syscall <id> instruction. There are several tools that arrange all this for us, SysWhispers2 and SysWhisper3 are two great examples. From an evasion perspective, there are two issues with calling direct system calls:

  1. Your binary ends up with having the syscall instruction, which is easy to statically detect (a.k.a “mark of the syscall”, more in “SysWhispers is dead, long live SysWhispers!”).
  2. Unlike benign use of a system call that is called through its ntdll.dll equivalent, the return address of the system call does not point to ntdll.dll. Instead, it points to our code from where we called the syscall, which resides in memory regions outside of ntdll.dll. This is an indicator of a system call that is not called through ntdll.dll, which is suspicious.

To overcome these issues we can do the following:

  1. Implement an egg hunter mechanism. Replace the syscall instruction with the egg (some random unique identifiable pattern) and at runtime, search for this egg in memory and replace it with the syscall instruction using the ReadProcessMemory and WriteProcessMemory WINAPI calls. Thereafter, we can use direct system calls normally. This technique has been implemented by klezVirus.
  2. Instead of calling the syscall instruction from our own code, we search for the syscall instruction in ntdll.dll and jump to that memory address once we’ve prepared the stack to call the system call. This will result in an return address in RIP that points to ntdll.dll memory regions.

Both techniques are part of SysWhisper3.

8. Removing hooks in ntdll.dll

Another nice technique to evade EDR hooks in ntdll.dll is to overwrite the loaded ntdll.dll that is loaded by default (and hooked by the EDR) with a fresh copy from ntdll.dllntdll.dll is the first DLL that gets loaded by any Windows process. EDR solutions make sure their DLL is loaded shortly after, which puts all the hooks in place in the loaded ntdll.dll before our own code will execute.

If our code loads a fresh copy of ntdll.dll in memory afterwards, those EDR hooks will be overwritten. RefleXXion is a C++ library that implements the research done for this technique by MDSec. RelfeXXion uses direct system calls NtOpenSection and NtMapViewOfSection to get a handle to a clean ntdll.dll in \KnownDlls\ntdll.dll (registry path with previously loaded DLLs). It then overwrites the .TEXT section of the loaded ntdll.dll, which flushes out the EDR hooks.

I recommend to use adjust the RefleXXion library to use the same trick as described above in section 7.

9. Spoofing the thread call stack

The next two sections cover two techniques that provide evasions against detecting our shellcode in memory. Due to the beaconing behaviour of an implant, for a majority of the time the implant is sleeping, waiting for incoming tasks from its operator. During this time the implant is vulnerable for memory scanning techniques from the EDR. The first of the two evasions described in this post is spoofing the thread call stack.

When the implant is sleeping, its thread return address is pointing to our shellcode residing in memory. By examining the return addresses of threads in a suspicious process, our implant shellcode can be easily identified. In order to avoid this, want to break this connection between the return address and shellcode.

We can do so by hooking the Sleep() function. When that hook is called (by the implant/beacon shellcode), we overwrite the return address with 0x0 and call the original Sleep() function. When Sleep() returns, we put the original return address back in place so the thread returns to the correct address to continue execution. Mariusz Banach has implemented this technique in his ThreadStackSpoofer project. This repo provides much more detail on the technique and also outlines some caveats.

We can observe the result of spoofing the thread call stack in the two screenshots below, where the non-spoofed call stack points to non-backed memory locations and a spoofed thread call stack points to our hooked Sleep (MySleep) function and “cuts off” the rest of the call stack.

thread not spoofed

Default beacon thread call stack.

thread spoofed

Spoofed beacon thread call stack.

10. In-memory encryption of beacon

The other evasion for in-memory detection is to encrypt the implant’s executable memory regions while sleeping. Using the same sleep hook as described in the section above, we can obtain the shellcode memory segment by examining the caller address (the beacon code that calls Sleep() and therefore our MySleep() hook).

If the caller memory region is MEM_PRIVATE and EXECUTABLE and roughly the size of our shellcode, then the memory segment is encrypted with a XOR function and Sleep() is called. Then Sleep() returns, it decrypts the memory segment and returns to it.

Another technique is to register a Vectored Exception Handler (VEH) that handles NO_ACCESS violation exceptions, decrypts the memory segments and changes the permissions to RX. Then just before sleeping, mark the memory segments as NO_ACCESS, so that when Sleep() returns, it throws a memory access violation exception.

Because we registered a VEH, the exception is handled within that thread context and can be resumed at the exact same location the exception was thrown. The VEH can simply decrypt and change the permissions back to RX and the implant can continue execution. This technique prevents a detectible Sleep() hook being in place when the implant is sleeping.

Mariusz Banach has also implemented this technique in ShellcodeFluctuation.

11. A custom reflective loader

The beacon shellcode that we execute in this loader ultimately is a DLL that needs to be executed in memory. Many C2 frameworks leverage Stephen Fewer’s ReflectiveLoader. There are many well written explanations of how exactly a relfective DLL loader works, and Stephen Fewer’s code is also well documented, but in short a Reflective Loader does the following:

  1. Resolve addresses to necessary kernel32.dll WINAPIs required for loading the DLL (e.g. VirtualAllocLoadLibraryA etc.)
  2. Write the DLL and its sections to memory
  3. Build up the DLL import table, so the DLL can call ntdll.dll and kernel32.dll WINAPIs
  4. Load any additional library’s and resolve their respective imported function addresses
  5. Call the DLL entrypoint

Cobalt Strike added support for a custom way for reflectively loading a DLL in memory that allows a red team operator to customize the way a beacon DLL gets loaded and add evasion techniques. Bobby Cooke and Santiago P built a stealthy loader (BokuLoader) using Cobalt Strike’s UDRL which I’ve used in my loader. BokuLoader implements several evasion techniques:

  • Limit calls to GetProcAddress() (commonly EDR hooked WINAPI call to resolve a function address, as we do in section 4)
  • AMSI & ETW bypasses
  • Use only direct system calls
  • Use only RW or RX, and no RWX (EXECUTE_READWRITE) permissions
  • Removes beacon DLL headers from memory

Make sure to uncomment the two defines to leverage direct system calls via HellsGate & HalosGate and bypass ETW and AMSI (not really necessary, as we’ve already disabled ETW and are not injecting the loader into another process).

12. OpSec configurations in your Malleable profile

In your Malleable C2 profile, make sure the following options are configured, which limit the use of RWX marked memory (suspicious and easily detected) and clean up the shellcode after beacon has started.

    set startrwx        "false";
    set userwx          "false";
    set cleanup         "true";
    set stomppe         "true";
    set obfuscate       "true";
    set sleep_mask      "true";
    set smartinject     "true";

Conclusions

Combining these techniques allow you to bypass (among others) Microsoft Defender for Endpoint and CrowdStrike Falcon with 0 detections (tested mid April 2022), which together with SentinelOne lead the endpoint protection industry.

crowdstrike bypass

CrowdStrike Falcon with 0 alerts.

windef bypass

Windows Defender (and also Microsoft Defender for Endpoint, not screenshotted) with 0 alerts.

Of course this is just one and the first step in fully compromising an endpoint, and this doesn’t mean “game over” for the EDR solution. Depending on what post-exploitation activity/modules the red team operator choses next, it can still be “game over” for the implant.

In general, either run BOFs, or tunnel post-ex tools through the implant’s SOCKS proxy feature. Also consider putting the EDR hooks patches back in place in our Sleep() hook to avoid detection of unhooking, as well as removing the ETW/AMSI patches.

It’s a cat and mouse game, and the cat is undoubtedly getting better.

Vincent Van Mieghem

Continue reading Evading industry leading endpoint protection in 2022

Explore
Drag