İnject DLL Reading.

Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
Üye
Katılım
16 Şub 2017
Mesajlar
13
Tepki puanı
0
Ödüller
8
9 HİZMET YILI
Belirttiğim bir programa inject edilen DLL leri okuyacak, arasında D3D9.DLL var ise programı kapatacak.

Yardımcı olabilir msniz?

It will read the DLLs injected into a program I specified, and if there is D3D9.DLL in between, it will close the program.

Help Me.
İf döngüsü dönmesi gerektiğini biliyorum, sadece DLL leri okuyan bir kod lazım.
 
Üye
Katılım
23 Eyl 2020
Mesajlar
36
Tepki puanı
27
5 HİZMET YILI
Kod:
[CODE=cpp
#include "Utils.h"

typedef void(*LdrInitializeThunk)(PCONTEXT NormalContext, PVOID SystemArgument1, PVOID SystemArgument2);
static LdrInitializeThunk LdrInitializeThunk_ = nullptr;


typedef NTSTATUS(WINAPI* lpNtQueryInformationThread)(HANDLE, LONG, PVOID, ULONG, PULONG);
void LdrInitializeThunk_t(PCONTEXT NormalContext, PVOID SystemArgument1, PVOID SystemArgument2)
{
    auto GetThreadStartAddress = [](HANDLE hThread) -> DWORD {
        auto NtQueryInformationThread = (lpNtQueryInformationThread)GetProcAddress(LoadLibraryA("ntdll"), "NtQueryInformationThread");
        assert(NtQueryInformationThread);

        DWORD dwCurrentThreadAddress = 0;
        NtQueryInformationThread(hThread, 9 /* ThreadQuerySetWin32StartAddress */, &dwCurrentThreadAddress, sizeof(dwCurrentThreadAddress), NULL);
        return dwCurrentThreadAddress;
    };

    auto dwStartAddress = GetThreadStartAddress(NtCurrentThread);
    printf("[*] Process içerisinde bir thread oluşturuldu! Start address: %p\n", (void*)dwStartAddress);

    auto dwThreadId = GetThreadId(NtCurrentThread);
    printf("\t* Thread: %u - Suspended: %d\n", dwThreadId, CUtils::IsSuspendedThread(dwThreadId));

    CONTEXT ctx = { 0 };
    ctx.ContextFlags = CONTEXT_ALL;
    if (GetThreadContext(NtCurrentThread, &ctx))
    {
        auto bHasDebugRegister = (ctx.Dr0 || ctx.Dr1 || ctx.Dr2 || ctx.Dr3 || ctx.Dr7);
        printf("\t* Context; Debug register: %d Eip: %p Eax: %p\n", bHasDebugRegister, (void*)ctx.Eip, (void*)ctx.Eax);
    }

    MODULEINFO user32ModInfo = { 0 };
    if (GetModuleInformation(NtCurrentProcess, LoadLibraryA("user32"), &user32ModInfo, sizeof(user32ModInfo)))
    {
        DWORD dwUser32Low = (DWORD)user32ModInfo.lpBaseOfDll;
        DWORD dwUser32Hi = (DWORD)user32ModInfo.lpBaseOfDll + user32ModInfo.SizeOfImage;
        if (dwStartAddress >= dwUser32Low && dwStartAddress <= dwUser32Hi)
            printf("# UYARI # User32.dll içerisinde dwStartAddress\n");
    }

    if (dwStartAddress == (DWORD)LoadLibraryA)
        printf("# UYARI # dwStartAddress == LoadLibraryA\n");

    else if (dwStartAddress == (DWORD)LoadLibraryW)
        printf("# UYARI # dwStartAddress == LoadLibraryW\n");

    else if (dwStartAddress == (DWORD)LoadLibraryExA)
        printf("# UYARI # dwStartAddress == LoadLibraryExA\n");

    else if (dwStartAddress == (DWORD)LoadLibraryExW)
        printf("# UYARI # dwStartAddress == LoadLibraryExW\n");

    else if (dwStartAddress == (DWORD)GetProcAddress(LoadLibraryA("ntdll"), "RtlUserThreadStart"))
        printf("# UYARI # dwStartAddress == RtlUserThreadStart\n");

    else if (dwStartAddress == (DWORD)GetProcAddress(LoadLibraryA("ntdll"), "NtCreateThread"))
        printf("# UYARI # dwStartAddress == NtCreateThread\n");

    else if (dwStartAddress == (DWORD)GetProcAddress(LoadLibraryA("ntdll"), "NtCreateThreadEx"))
        printf("# UYARI # dwStartAddress == NtCreateThreadEx\n");

    else if (dwStartAddress == (DWORD)GetProcAddress(LoadLibraryA("ntdll"), "RtlCreateUserThread"))
        printf("# UYARI # dwStartAddress == RtlCreateUserThread\n");

    MEMORY_BASIC_INFORMATION mbi = { 0 };
    if (VirtualQuery((LPCVOID)dwStartAddress, &mbi, sizeof(mbi)))
    {
        if (mbi.Type != MEM_IMAGE)
            printf("# UYARI # mbi.Type != MEM_IMAGE\n");

        if (dwStartAddress == (DWORD)mbi.AllocationBase)
            printf("# UYARI # dwStartAddress == mbi.AllocationBase\n");
    }

    if (CUtils::IsLoadedAddress(dwStartAddress))
        printf("# UYARI # IsLoadedAddress(dwStartAddress)\n");

    if (CUtils::GetThreadOwnerProcessId(dwThreadId) != GetCurrentProcessId())
        printf("# UYARI # GetThreadOwnerProcessId(dwThreadId) != GetCurrentProcessId()\n");

    IMAGE_SECTION_HEADER * pCurrentSecHdr = (IMAGE_SECTION_HEADER*)dwStartAddress;
    if (pCurrentSecHdr)
    {
        BOOL IsMonitored =
            (pCurrentSecHdr->Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pCurrentSecHdr->Characteristics & IMAGE_SCN_MEM_READ) &&
            (pCurrentSecHdr->Characteristics & IMAGE_SCN_CNT_CODE) && !(pCurrentSecHdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE);

        if (IsMonitored)
            printf("# UYARI # Remote Code!\n");
    }

    return LdrInitializeThunk_(NormalContext, SystemArgument1, SystemArgument2);
}

void InitializeThreadCheck()
{
    auto hNtdll = LoadLibraryA("ntdll.dll");
    printf("hNtdll: %p\n", hNtdll);
    assert(hNtdll);

    auto LdrInitializeThunk_o = reinterpret_cast<LdrInitializeThunk>(GetProcAddress(hNtdll, "LdrInitializeThunk"));
    printf("LdrInitializeThunk: %p\n", LdrInitializeThunk_o);
    assert(LdrInitializeThunk_o);

    LdrInitializeThunk_ = reinterpret_cast<LdrInitializeThunk>(CUtils::DetourFunc(reinterpret_cast<PBYTE>(LdrInitializeThunk_o), reinterpret_cast<PBYTE>(LdrInitializeThunk_t), 5));
    printf("LdrInitializeThunk(detour): %p\n", LdrInitializeThunk_);

    DWORD dwOld = 0;
    auto bProtectRet = VirtualProtect(LdrInitializeThunk_, 5, PAGE_EXECUTE_READWRITE, &dwOld);
    assert(bProtectRet);
}

Kod:
[CODE=cpp]#pragma once

class CThreadEnumerator
{
    public:
        CThreadEnumerator(DWORD dwProcessId);
        ~CThreadEnumerator();

        SYSTEM_PROCESS_INFORMATION * GetProcInfo();
        SYSTEM_THREAD_INFORMATION  * GetThreadList(SYSTEM_PROCESS_INFORMATION * procInfo);
        DWORD                         GetThreadCount(SYSTEM_PROCESS_INFORMATION * procInfo);

        SYSTEM_THREAD_INFORMATION  * FindThread(SYSTEM_PROCESS_INFORMATION * procInfo, DWORD dwThreadId);

    protected:
        BYTE * InitializeQuery();

    private:
        DWORD  m_dwProcessId;
        BYTE * m_Cap;
};

Kod:
 = 0xE9;
    *(DWORD*)(jmp + 1) = (DWORD)(src + len - jmp) - 5;

    src[0] = 0xE9;
    *(DWORD*)(src + 1) = (DWORD)(dst - src) - 5;

    VirtualProtect(src, len, dwback, &dwback);

    return (jmp - len);
}

PVOID CUtils::GetModuleAddressFromName(const wchar_t* c_wszName)
{
    PPEB pPEB = (PPEB)__readfsdword(0x30);
    PLDR_DATA_TABLE_ENTRY Current = NULL;
    PLIST_ENTRY CurrentEntry = pPEB->Ldr->InMemoryOrderModuleList.Flink;

    while (CurrentEntry != &pPEB->Ldr->InMemoryOrderModuleList && CurrentEntry != NULL)
    {
        Current = CONTAINING_RECORD(CurrentEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);

        if (wcsstr(Current->FullDllName.Buffer, c_wszName))
            return Current->DllBase;

        CurrentEntry = CurrentEntry->Flink;
    }
    return nullptr;
}
bool CUtils::IsLoadedAddress(DWORD dwAddress)
{
    PPEB pPEB = (PPEB)__readfsdword(0x30);
    PLDR_DATA_TABLE_ENTRY Current = NULL;
    PLIST_ENTRY CurrentEntry = pPEB->Ldr->InMemoryOrderModuleList.Flink;

    while (CurrentEntry != &pPEB->Ldr->InMemoryOrderModuleList && CurrentEntry != NULL)
    {
        Current = CONTAINING_RECORD(CurrentEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
        if (dwAddress == (DWORD)Current->DllBase)
            return true;

        CurrentEntry = CurrentEntry->Flink;
    }
    return false;
}

BOOL bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask)
{
    for (; *szMask; ++szMask, ++pData, ++bMask)
        if (*szMask == 'x' && *pData != *bMask)
            return FALSE;
    return (*szMask) == NULL;
}
DWORD CUtils::FindPattern(DWORD dwAddress, DWORD dwLen, BYTE *bMask, char * szMask)
{
    for (DWORD i = 0; i < dwLen; i++)
        if (bDataCompare((BYTE*)(dwAddress + i), bMask, szMask))
            return (DWORD)(dwAddress + i);
    return 0;
}

DWORD CUtils::GetThreadOwnerProcessId(DWORD dwThreadID)
{
    auto hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);
    if (!hSnap || hSnap == INVALID_HANDLE_VALUE)
        return 0;

    THREADENTRY32 ti = { 0 };
    ti.dwSize = sizeof(ti);

    if (Thread32First(hSnap, &ti))
    {
        do {
            if (dwThreadID == ti.th32ThreadID) {
                CloseHandle(hSnap);
                return ti.th32OwnerProcessID;
            }
        } while (Thread32Next(hSnap, &ti));
    }

    CloseHandle(hSnap);
    return 0;
}

C++:
#pragma once

class CUtils
{
    public:
        static PVOID GetModuleAddressFromName(const wchar_t* c_wszName);
        static bool  IsLoadedAddress(DWORD dwAddress);

        static PVOID DetourFunc(BYTE *src, const BYTE *dst, const int len);
        static DWORD FindPattern(DWORD dwAddress, DWORD dwLen, BYTE *bMask, char * szMask);

        static bool  IsSuspendedThread(DWORD dwThreadId);

        static DWORD GetThreadOwnerProcessId(DWORD dwThreadID);
};

C++:
#pragma once
#include <Windows.h>
#include <iostream>
#include <assert.h>
#include <Psapi.h>
#include <TlHelp32.h>

extern void InitializeDLLCheck();
extern void InitializeThreadCheck();

#define STATUS_INFO_LENGTH_MISMATCH    ((NTSTATUS) 0xC0000004)

#define NtCurrentProcess            ((HANDLE)(LONG_PTR)-1)
#define NtCurrentThread                ((HANDLE)(LONG_PTR)-2)

namespace
{
    typedef struct _UNICODE_STRING {
        USHORT Length;
        USHORT MaximumLength;
        PWSTR  Buffer;
    } UNICODE_STRING;
    typedef UNICODE_STRING *PUNICODE_STRING;

    typedef struct _LDR_DATA_TABLE_ENTRY {
        PVOID Reserved1[2];
        LIST_ENTRY InMemoryOrderLinks;
        PVOID Reserved2[2];
        PVOID DllBase;
        PVOID Reserved3[2];
        UNICODE_STRING FullDllName;
        BYTE Reserved4[8];
        PVOID Reserved5[3];
        union {
            ULONG CheckSum;
            PVOID Reserved6;
        } DUMMYUNIONNAME;
        ULONG TimeDateStamp;
    } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;

    typedef
        VOID
        (NTAPI *PPS_POST_PROCESS_INIT_ROUTINE) (
            VOID
            );


    typedef struct _PEB_LDR_DATA {
        BYTE Reserved1[8];
        PVOID Reserved2[3];
        LIST_ENTRY InMemoryOrderModuleList;
    } PEB_LDR_DATA, *PPEB_LDR_DATA;

    typedef struct _RTL_USER_PROCESS_PARAMETERS {
        BYTE Reserved1[16];
        PVOID Reserved2[10];
        UNICODE_STRING ImagePathName;
        UNICODE_STRING CommandLine;
    } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;

    typedef struct _PEB {
        BYTE Reserved1[2];
        BYTE BeingDebugged;
        BYTE Reserved2[1];
        PVOID Reserved3[2];
        PPEB_LDR_DATA Ldr;
        PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
        BYTE Reserved4[104];
        PVOID Reserved5[52];
        PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
        BYTE Reserved6[128];
        PVOID Reserved7[1];
        ULONG SessionId;
    } PEB, *PPEB;

    typedef LONG KPRIORITY;

    enum KWAIT_REASON
    {
        Suspended = 5,
    };

    enum THREAD_STATE
    {
        Running = 2,
        Waiting = 5,
    };

    typedef struct _CLIENT_ID
    {
        HANDLE UniqueProcess;
        HANDLE UniqueThread;
    } CLIENT_ID, *PCLIENT_ID;

    typedef struct _SYSTEM_THREAD_INFORMATION
    {
        LARGE_INTEGER KernelTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER CreateTime;
        ULONG WaitTime;
        PVOID StartAddress;
        CLIENT_ID ClientId;
        KPRIORITY Priority;
        LONG BasePriority;
        ULONG ContextSwitches;
        ULONG ThreadState;
        ULONG WaitReason;
    } SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;

    typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION
    {
        SYSTEM_THREAD_INFORMATION ThreadInfo;
        PVOID StackBase;
        PVOID StackLimit;
        PVOID Win32StartAddress;
        PVOID TebAddress;
        ULONG_PTR Reserved2;
        ULONG_PTR Reserved3;
        ULONG_PTR Reserved4;
    } SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;

    typedef struct _SYSTEM_PROCESS_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG NumberOfThreads;
        LARGE_INTEGER SpareLi1;
        LARGE_INTEGER SpareLi2;
        LARGE_INTEGER SpareLi3;
        LARGE_INTEGER CreateTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER KernelTime;
        UNICODE_STRING ImageName;
        KPRIORITY BasePriority;
        HANDLE UniqueProcessId;
        HANDLE InheritedFromUniqueProcessId;
        ULONG HandleCount;
        ULONG SessionId;
        ULONG_PTR PageDirectoryBase;
        SIZE_T PeakVirtualSize;
        SIZE_T VirtualSize;
        ULONG PageFaultCount;
        SIZE_T PeakWorkingSetSize;
        SIZE_T WorkingSetSize;
        SIZE_T QuotaPeakPagedPoolUsage;
        SIZE_T QuotaPagedPoolUsage;
        SIZE_T QuotaPeakNonPagedPoolUsage;
        SIZE_T QuotaNonPagedPoolUsage;
        SIZE_T PagefileUsage;
        SIZE_T PeakPagefileUsage;
        SIZE_T PrivatePageCount;
        LARGE_INTEGER ReadOperationCount;
        LARGE_INTEGER WriteOperationCount;
        LARGE_INTEGER OtherOperationCount;
        LARGE_INTEGER ReadTransferCount;
        LARGE_INTEGER WriteTransferCount;
        LARGE_INTEGER OtherTransferCount;
        SYSTEM_THREAD_INFORMATION Threads[1];
    } SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;


    typedef enum _SYSTEM_INFORMATION_CLASS
    {
        SystemBasicInformation,
        SystemProcessorInformation,
        SystemPerformanceInformation,
        SystemTimeOfDayInformation,
        SystemPathInformation,
        SystemProcessInformation,
        SystemCallCountInformation,
        SystemDeviceInformation,
        SystemProcessorPerformanceInformation,
        SystemFlagsInformation,
        SystemCallTimeInformation,
        SystemModuleInformation,
        SystemLocksInformation,
        SystemStackTraceInformation,
        SystemPagedPoolInformation,
        SystemNonPagedPoolInformation,
        SystemHandleInformation,
        SystemObjectInformation,
        SystemPageFileInformation,
        SystemVdmInstemulInformation,
        SystemVdmBopInformation,
        SystemFileCacheInformation,
        SystemPoolTagInformation,
        SystemInterruptInformation,
        SystemDpcBehaviorInformation,
        SystemFullMemoryInformation,
        SystemLoadGdiDriverInformation,
        SystemUnloadGdiDriverInformation,
        SystemTimeAdjustmentInformation,
        SystemSummaryMemoryInformation,
        SystemMirrorMemoryInformation,
        SystemPerformanceTraceInformation,
        SystemObsolete0,
        SystemExceptionInformation,
        SystemCrashDumpStateInformation,
        SystemKernelDebuggerInformation,
        SystemContextSwitchInformation,
        SystemRegistryQuotaInformation,
        SystemExtendServiceTableInformation,
        SystemPrioritySeperation,
        SystemVerifierAddDriverInformation,
        SystemVerifierRemoveDriverInformation,
        SystemProcessorIdleInformation,
        SystemLegacyDriverInformation,
        SystemCurrentTimeZoneInformation,
        SystemLookasideInformation,
        SystemTimeSlipNotification,
        SystemSessionCreate,
        SystemSessionDetach,
        SystemSessionInformation,
        SystemRangeStartInformation,
        SystemVerifierInformation,
        SystemVerifierThunkExtend,
        SystemSessionProcessInformation,
        SystemLoadGdiDriverInSystemSpace,
        SystemNumaProcessorMap,
        SystemPrefetcherInformation,
        SystemExtendedProcessInformation,
        SystemRecommendedSharedDataAlignment,
        SystemComPlusPackage,
        SystemNumaAvailableMemory,
        SystemProcessorPowerInformation,
        SystemEmulationBasicInformation,
        SystemEmulationProcessorInformation,
        SystemExtendedHandleInformation,
        SystemLostDelayedWriteInformation,
        SystemBigPoolInformation,
        SystemSessionPoolTagInformation,
        SystemSessionMappedViewInformation,
        SystemHotpatchInformation,
        SystemObjectSecurityMode,
        SystemWatchdogTimerHandler,
        SystemWatchdogTimerInformation,
        SystemLogicalProcessorInformation,
        SystemWow64SharedInformationObsolete,
        SystemRegisterFirmwareTableInformationHandler,
        SystemFirmwareTableInformation,
        SystemModuleInformationEx,
        SystemVerifierTriageInformation,
        SystemSuperfetchInformation,
        SystemMemoryListInformation,
        SystemFileCacheInformationEx,
        SystemThreadPriorityClientIdInformation,
        SystemProcessorIdleCycleTimeInformation,
        SystemVerifierCancellationInformation,
        SystemProcessorPowerInformationEx,
        SystemRefTraceInformation,
        SystemSpecialPoolInformation,
        SystemProcessIdInformation,
        SystemErrorPortInformation,
        SystemBootEnvironmentInformation,
        SystemHypervisorInformation,
        SystemVerifierInformationEx,
        SystemTimeZoneInformation,
        SystemImageFileExecutionOptionsInformation,
        SystemCoverageInformation,
        SystemPrefetchPatchInformation,
        SystemVerifierFaultsInformation,
        SystemSystemPartitionInformation,
        SystemSystemDiskInformation,
        SystemProcessorPerformanceDistribution,
        SystemNumaProximityNodeInformation,
        SystemDynamicTimeZoneInformation,
        SystemCodeIntegrityInformation,
        SystemProcessorMicrocodeUpdateInformation,
        SystemProcessorBrandString,
        SystemVirtualAddressInformation,
        SystemLogicalProcessorAndGroupInformation,
        SystemProcessorCycleTimeInformation,
        SystemStoreInformation,
        SystemRegistryAppendString,
        SystemAitSamplingValue,
        SystemVhdBootInformation,
        SystemCpuQuotaInformation,
        SystemNativeBasicInformation,
        SystemSpare1,
        SystemLowPriorityIoInformation,
        SystemTpmBootEntropyInformation,
        SystemVerifierCountersInformation,
        SystemPagedPoolInformationEx,
        SystemSystemPtesInformationEx,
        SystemNodeDistanceInformation,
        SystemAcpiAuditInformation,
        SystemBasicPerformanceInformation,
        SystemQueryPerformanceCounterInformation,
        SystemSessionBigPoolInformation,
        SystemBootGraphicsInformation,
        SystemScrubPhysicalMemoryInformation,
        SystemBadPageInformation,
        SystemProcessorProfileControlArea,
        SystemCombinePhysicalMemoryInformation,
        SystemEntropyInterruptTimingCallback,
        SystemConsoleInformation,
        SystemPlatformBinaryInformation,
        SystemThrottleNotificationInformation,
        SystemHypervisorProcessorCountInformation,
        SystemDeviceDataInformation,
        SystemDeviceDataEnumerationInformation,
        SystemMemoryTopologyInformation,
        SystemMemoryChannelInformation,
        SystemBootLogoInformation,
        SystemProcessorPerformanceInformationEx,
        SystemSpare0,
        SystemSecureBootPolicyInformation,
        SystemPageFileInformationEx,
        SystemSecureBootInformation,
        SystemEntropyInterruptTimingRawInformation,
        SystemPortableWorkspaceEfiLauncherInformation,
        SystemFullProcessInformation,
        SystemKernelDebuggerInformationEx,
        SystemBootMetadataInformation,
        SystemSoftRebootInformation,
        SystemElamCertificateInformation,
        SystemOfflineDumpConfigInformation,
        SystemProcessorFeaturesInformation,
        SystemRegistryReconciliationInformation,
        SystemEdidInformation,
        MaxSystemInfoClass
    } SYSTEM_INFORMATION_CLASS;
}

Kod:
Bu işini görecektir.
 
Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
Üst