C++實現ETW進行程序變動監控

2022-07-12 18:04:36

C++實現ETW進行程序變動監控

文章地址:https://www.cnblogs.com/Icys/p/EtwProcess.html

何為Etw

ETW(Event Tracing for Windows)提供了一種對使用者層應用程式和核心層驅動建立的事件物件的跟蹤記錄機制。為開發者提供了一套快速、可靠、通用的一系列事件跟蹤特性。

百度百科

前言

一直想研究一種監控程序的方法,但\(wmi/列舉程序\)的方法,要麼反應太慢,要麼佔用高。最近看到有人用\(易語言\)完成了Etw對程序變動監控的實現。

但是一直沒看到\(C++\)的實現,於是決定將\(易語言\)翻譯為\(C++\)

易語言程式碼地址

程式碼

直接上翻譯的程式碼

#include <iostream>
#include <string>
#include <cstring>
#include <windows.h>
#include <evntrace.h>
#include <psapi.h>
#include <direct.h>
#include <evntcons.h>
using namespace std;

char SESSION_NAME_FILE[] = "Sample_Process";

const UCHAR _Flag[] = { 173, 74, 129, 158, 4, 50, 210, 17, 154, 130, 0, 96, 8, 168, 105, 57 };

EVENT_TRACE_PROPERTIES m_TraceConfig;

UCHAR m_pTraceConfig[2048];

char m_File[256];

BOOL m_DoWhile;

TRACEHANDLE m_hTraceHandle;

ULONG64 m_hTraceHandle_econt[1];

TRACEHANDLE m_hSessionHandle;

string Unicode_To_Ansi(wstring strValue)
{
    static CHAR sBuff[1024] = { 0 };
    int iRet = WideCharToMultiByte(CP_ACP, 0, strValue.c_str(), -1, sBuff, sizeof(sBuff), NULL, NULL);
    if (iRet > 0) {
        return string(sBuff);
    }
    return "";
}

VOID WINAPI MyProcessRecordEvents(PEVENT_RECORD EventRecord)
{
    switch (EventRecord->EventHeader.EventDescriptor.Id)
    {
    case 1://建立程序
        cout << "建立程序!進行建立進行的程序ID:" <<
            EventRecord->EventHeader.ProcessId <<
            ",執行緒ID:" <<
            EventRecord->EventHeader.ThreadId <<
            ",程序SessionID:" <<
            *(ULONG*)(((PUCHAR)EventRecord->UserData)+32)<<
            ",建立的程序ID:"<<
            *(ULONG*)(((PUCHAR)EventRecord->UserData) + 0) <<
            ",建立的程序路徑:"<<
            Unicode_To_Ansi(  wstring((wchar_t*)(((PUCHAR)EventRecord->UserData) + 60)))
            <<endl;
        break;
    case 2://程序退出
        cout << "程序退出!程序ID:" <<
            EventRecord->EventHeader.ProcessId <<
            ",執行緒ID:" <<
            EventRecord->EventHeader.ThreadId <<
            ", 程序名:"<<
            ((LPSTR)EventRecord->UserData) + 84
            <<endl;
        break;
        cout << "程序ID:" << EventRecord->EventHeader.ProcessId << ",未知的行為:0x"<<hex<<EventRecord->EventHeader.EventDescriptor.Id << endl;
    default:

        break;
    }
}

void CloseEtw()
{
    ULONG l_result = StopTraceA(m_hSessionHandle, SESSION_NAME_FILE, (PEVENT_TRACE_PROPERTIES)(m_pTraceConfig + 8));
    if (m_hTraceHandle != NULL)
    {
        CloseTrace(m_hTraceHandle);
    }
}

DWORD WINAPI OpenEtw(LPVOID lpThreadParameter)
{
    m_DoWhile = TRUE;

    _getcwd(m_File, sizeof(m_File));

    strcat(m_File, "\\MyFile.etl");
    m_TraceConfig.Wnode.BufferSize = 1024;
    m_TraceConfig.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
    m_TraceConfig.Wnode.ClientContext = 3;
    m_TraceConfig.BufferSize = 1;
    m_TraceConfig.MinimumBuffers = 16;
    m_TraceConfig.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;

    m_TraceConfig.LoggerNameOffset = 120;
    m_TraceConfig.FlushTimer = 1;

    RtlMoveMemory(m_pTraceConfig + 8, &m_TraceConfig, 120);
    RtlCopyMemory(m_pTraceConfig + 128, SESSION_NAME_FILE, sizeof(SESSION_NAME_FILE));
    RtlCopyMemory(m_pTraceConfig + 128 + sizeof(SESSION_NAME_FILE), m_File, strlen(m_File));
    RtlCopyMemory(m_pTraceConfig + 28, _Flag, sizeof(_Flag));

    ULONG l_result = StartTraceA(&m_hSessionHandle, SESSION_NAME_FILE, (PEVENT_TRACE_PROPERTIES)(m_pTraceConfig + 8));
    
    if (m_hSessionHandle == NULL && l_result == ERROR_ACCESS_DENIED)
    {
        cout << "StartTraceA失敗!原因:無管理員許可權!" << endl;
        return 0;
    }
    else if (m_hSessionHandle == NULL && l_result == ERROR_ALREADY_EXISTS)
    {

     m_hSessionHandle = 44;//輸入上一次終止時候的控制程式碼
        CloseEtw();
     
        cout << "StartTraceA失敗!原因:已經有Etw事件進行資料跟蹤!請使用上方遮蔽程式碼關閉事件或者使用 計算機管理 停用事件:Sample_Process" << endl;
        ControlTraceA(m_hSessionHandle, SESSION_NAME_FILE, (PEVENT_TRACE_PROPERTIES)(m_pTraceConfig + 8), 1);
        return 0;
    }
    cout << "hSessionHandle: " << m_hSessionHandle << endl;
    const UCHAR m_ProcessGUID[] = { 214, 44, 251, 34, 123, 14, 43, 66, 160, 199, 47, 173, 31, 208, 231, 22 }; // PsProvGuid
    l_result = EnableTraceEx((LPCGUID)(m_ProcessGUID), 0, m_hSessionHandle, 1, 0, 16, 0, 0, 0);         //這裡MatchAnyKeyword的64其實是0x40,表示 #KERNEL_KEYWORDS_IMAGE

    EVENT_TRACE_LOGFILEA m_Logfile;
    ZeroMemory(&m_Logfile, sizeof(m_Logfile));
    m_Logfile.LoggerName = SESSION_NAME_FILE;
    *((ULONG*)((PUCHAR)&m_Logfile + 20)) = 268439808;
    m_Logfile.EventRecordCallback = MyProcessRecordEvents;
    m_Logfile.Context = (PVOID)0x114514;//隨便輸入一個數就好了
    SetLastError(0);
    m_hTraceHandle = OpenTraceA(&m_Logfile);

    cout << "開始監視!" << endl;
    m_hTraceHandle_econt[0] = m_hTraceHandle;
    ULONG rc = ProcessTrace(m_hTraceHandle_econt, 1, 0, 0);
    return 0;
}

int main()
{
    CreateThread(NULL, NULL, OpenEtw, NULL, NULL, NULL);
    //Sleep(10000);
    system("pause");
    CloseEtw();
    return 0;
}

注意事項

  1. 必須給管理員許可權

  2. 請正常退出(按任意鍵),否則Trace不會自己關

其他

作者(本人)水平有限,部分翻譯可能有誤,程式碼有問題可以直接回復我。

以後有時間可能會考慮翻譯一下這個作者其他的關於Etw的例子,畢竟Etw實現的這些功能都很有意思,並且都比較高階。