티스토리 뷰

개발/WIN32-MFC

[ WIN ] DLL INJECTION

-=HaeJuK=- 2024. 4. 22. 13:14
반응형

DLL 인젝션(DLL Injection)은 다른 프로세스의 주소 공간에 동적으로 라이브러리(DLL 파일)를 삽입하는 기술입니다. 이 방법은 주로 소프트웨어 개발과 디버깅, 리버스 엔지니어링, 또는 때때로 보안 테스트에 사용됩니다. 하지만, 악의적 목적으로 사용될 수도 있기 때문에 책임감 있는 사용이 중요합니다.

DLL 인젝션의 기본 원리

DLL 인젝션을 수행하는 과정은 일반적으로 다음 단계를 포함합니다:

  1. 대상 프로세스 식별: 인젝션을 수행할 프로세스의 식별자(Process ID, PID)를 얻습니다.
  2. 메모리 할당: 대상 프로세스의 주소 공간에 새로운 메모리를 할당합니다. 이 메모리는 DLL 경로를 저장하는 데 사용됩니다.
  3. DLL 경로 작성: 할당된 메모리에 DLL의 경로를 씁니다.
  4. 리모트 스레드 생성: CreateRemoteThread 함수를 사용하여 대상 프로세스 내에 새로운 스레드를 생성합니다. 이 스레드는 LoadLibrary API를 호출하여 DLL을 로드합니다.
//Header
#pragma once
class cInjector
{

public:
	static bool InjectDLL( DWORD _nProcessId, const std::wstring& _ssDllName );
	static bool EjectDLL( DWORD _nProcessId, const std::wstring& _ssDllName );

private:
	static HMODULE GetRemoteModuleHandle( DWORD _nProcessId, const std::wstring& _ssModuleName );
};
// CPP 
#include <windows.h>
#include <iostream>
#include <tlhelp32.h>

bool cInjector::InjectDLL( DWORD _nProcessId, const std::wstring& _ssDllPath ) 
{
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, _nProcessId );
    if( !hProcess )
    {
        std::wcerr << L"Failed to open process: " << GetLastError() << std::endl;
        return false;
    }
    
    // Get the handle of the module to eject
    HMODULE hMod = GetRemoteModuleHandle( _nProcessId, _ssDllPath );
    if( NULL != hMod ) 
    {
       bool bResult =  EjectDLL( _nProcessId , _ssDllPath );
       if( false == bResult )
       {
           return bResult;
       }
    }

    // Allocate memory in the target process
    LPVOID pLibRemote = VirtualAllocEx( hProcess, NULL, _ssDllPath.size() * sizeof( wchar_t ),
        MEM_COMMIT, PAGE_READWRITE );

    if( pLibRemote == NULL ) 
    {
        std::wcerr << L"Failed to allocate memory in target process: " << GetLastError() << std::endl;
        CloseHandle( hProcess );
        return false;
    }

    // Write the DLL path to the allocated memory
    SIZE_T written = 0;
    if( !WriteProcessMemory( hProcess, pLibRemote, (void*)_ssDllPath.c_str(),
        _ssDllPath.size() * sizeof( wchar_t ), &written ) ) {
        std::wcerr << L"Failed to write process memory: " << GetLastError() << std::endl;
        VirtualFreeEx( hProcess, pLibRemote, 0, MEM_RELEASE );
        CloseHandle( hProcess );
        return false;
    }

    // Load the DLL
    HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0,
        (LPTHREAD_START_ROUTINE)GetProcAddress( GetModuleHandle( L"kernel32.dll" ), "LoadLibraryW" ),
        pLibRemote, 0, NULL );
    
    if( !hThread )
    {
        std::wcerr << L"Failed to create remote thread in target process: " << GetLastError() << std::endl;
        VirtualFreeEx( hProcess, pLibRemote, 0, MEM_RELEASE );
        CloseHandle( hProcess );
        return false;
    }

    std::wcout << L"Successfully injected DLL." << std::endl;

    // Wait for the remote thread to terminate
    WaitForSingleObject( hThread, INFINITE );

    // Clean up
    VirtualFreeEx( hProcess, pLibRemote, 0, MEM_RELEASE );
    CloseHandle( hThread );
    CloseHandle( hProcess );

    return true;
}

bool cInjector::EjectDLL( DWORD _nProcessId, const std::wstring& _ssDllName ) 
{
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, _nProcessId );
    if( !hProcess ) 
    {
        std::wcerr << L"Failed to open process: " << GetLastError() << std::endl;
        return false;
    }

    // Get the handle of the module to eject
    HMODULE hMod = GetRemoteModuleHandle( _nProcessId, _ssDllName );
    if( !hMod ) 
    {
        std::wcerr << L"Failed to find module handle: " << _ssDllName << std::endl;
        CloseHandle( hProcess );
        return false;
    }

    // Get the address of FreeLibrary in Kernel32.dll
    LPVOID pFreeLibrary = (LPVOID)GetProcAddress( GetModuleHandle( L"kernel32.dll" ), "FreeLibrary" );
    if( !pFreeLibrary )
    {
        std::wcerr << L"Failed to get address of FreeLibrary." << std::endl;
        CloseHandle( hProcess );
        return false;
    }

    // Create a remote thread to run FreeLibrary
    HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0,
        (LPTHREAD_START_ROUTINE)pFreeLibrary, hMod, 0, NULL );
    if( !hThread )
    {
        std::wcerr << L"Failed to create remote thread: " << GetLastError() << std::endl;
        CloseHandle( hProcess );
        return false;
    }

    std::wcout << L"Successfully created thread to unload DLL." << std::endl;

    // Wait for the thread to exit
    WaitForSingleObject( hThread, INFINITE );

    // Check the exit code
    DWORD dwExitCode;
    if( !GetExitCodeThread( hThread, &dwExitCode ) || dwExitCode == 0 ) 
    {
        std::wcerr << L"Failed to unload DLL." << std::endl;
        CloseHandle( hThread );
        CloseHandle( hProcess );
        return false;
    }

    std::wcout << L"Successfully unloaded DLL." << std::endl;

    CloseHandle( hThread );
    CloseHandle( hProcess );

    return true;
}

HMODULE cInjector::GetRemoteModuleHandle( DWORD _nProcessId, const std::wstring& _ssModuleName )
{
    HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, _nProcessId );
    if( hSnap == INVALID_HANDLE_VALUE )
        return NULL;

    MODULEENTRY32W me = { sizeof( me ) };
    BOOL bModule = Module32FirstW( hSnap, &me );
    while( bModule )
    {
        if( me.szModule == _ssModuleName )
        {
            CloseHandle( hSnap );
            return me.hModule;
        }
        bModule = Module32NextW( hSnap, &me );
    }

    CloseHandle( hSnap );
    return NULL;
}
#include "cInjector.h"
int main()
{
    DWORD pid; // 대상 프로세스 ID
    std::cout << "Enter the PID of the target process: ";
    std::cin >> pid;

    const wchar* dllPath = L"path_to_dll.dll";
    if (cInjector::InjectDLL(pid, dllPath)) 
    {
        std::cout << "DLL was injected successfully." << std::endl;
    } 
    else
    {
        std::cerr << "DLL injection failed." << std::endl;
    }

    return 0;
}
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함