Исходник Basic DLL Injector/Loader.

Начинающий
Статус
Оффлайн
Регистрация
3 Авг 2023
Сообщения
20
Реакции[?]
2
Поинты[?]
5K
Basic DLL Injector/Loader

I know this is a super simple DLL Injector/Loader with no security and the most basic method to inject with. I've created this mostly for Legacy all is open source and you can do what ever you want with the code. To all the professional pasters that could have created a program like this in 1 line code and such things, save it I don't really care but if you have some useful information and or ways to improve this code please provide it.

There is some code left from another project so you guys know.

Main.cpp:
#include "Main.h"
enum class ErrorCodes {
    SUCCESS,
    FAILED_TO_OPEN_PROCESS,
    FAILED_TO_ALLOCATE_MEMORY,
    FAILED_TO_WRITE_DLL_PATH,
    FAILED_TO_GET_KERNEL32_HANDLE,
    FAILED_TO_GET_LOAD_LIBRARY_ADDRESS,
    FAILED_TO_CREATE_REMOTE_THREAD,
    FAILED_TO_INJECT_DLL
};

void Log(const std::string& message, bool writeToLogFile = false) {
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);

    struct tm time_info;
    localtime_s(&time_info, &now_c);

    char time_str[26];
    asctime_s(time_str, sizeof(time_str), &time_info);
    time_str[strlen(time_str) - 1] = '\0';

    std::cout << "[" << time_str << "] " << message << std::endl;

    if (writeToLogFile) {
        std::ofstream logFile("injector_log.txt", std::ios_base::app);
        logFile << "[" << time_str << "] " << message << std::endl;
    }
}

bool Injector::InjectDLL(DWORD processId, const std::wstring& dllPath, bool verbose) {
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);

    if (!hProcess) {
        DWORD errorCode = GetLastError();
        Log("Failed to open the target process. Error code: " + std::to_string(errorCode), true);
        return false;
    }

    LPVOID dllPathAddress = VirtualAllocEx(hProcess, nullptr, dllPath.size() * sizeof(wchar_t), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!dllPathAddress) {
        DWORD errorCode = GetLastError();
        Log("Failed to allocate memory in the target process. Error code: " + std::to_string(errorCode), true);
        CloseHandle(hProcess);
        return false;
    }

    if (!WriteProcessMemory(hProcess, dllPathAddress, dllPath.c_str(), dllPath.size() * sizeof(wchar_t), nullptr)) {
        DWORD errorCode = GetLastError();
        Log("Failed to write DLL path into the target process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
    if (!hKernel32) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the handle of kernel32.dll in the current process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    LPTHREAD_START_ROUTINE loadLibraryAddr = reinterpret_cast<LPTHREAD_START_ROUTINE>(GetProcAddress(hKernel32, "LoadLibraryW"));
    if (!loadLibraryAddr) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the address of LoadLibraryW function. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HANDLE hRemoteThread = CreateRemoteThread(hProcess, nullptr, 0, loadLibraryAddr, dllPathAddress, 0, nullptr);
    if (!hRemoteThread) {
        DWORD errorCode = GetLastError();
        Log("Failed to create a remote thread in the target process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    WaitForSingleObject(hRemoteThread, INFINITE);
    CloseHandle(hRemoteThread);

    VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
    CloseHandle(hProcess);

    return true;
}

bool Injector::GetProcessIdByName(const std::wstring& processName, DWORD& processId) {
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (Process32First(snapshot, &entry)) {
        do {
            if (_wcsicmp(entry.szExeFile, processName.c_str()) == 0) {
                processId = entry.th32ProcessID;
                CloseHandle(snapshot);
                return true;
            }
        } while (Process32Next(snapshot, &entry));
    }

    CloseHandle(snapshot);
    return false;
}

DWORD Injector::WaitForProcessFullyLoaded(const std::wstring& processName, bool verbose) {
    Log("Waiting for the target process to launch...");

    while (true) {
        DWORD processId;
        if (GetProcessIdByName(processName, processId)) {
            Log("Target process found. Process ID: " + std::to_string(processId));

            bool isFullyLoaded = true;

            if (isFullyLoaded) {
                return processId;
            }
        }
        Sleep(1000);
    }

    return 0;
}

int main() {
    const std::wstring targetProcessName = L"csgo.exe";
    const std::wstring dllPath = L"your_dll.dll";

    DWORD targetProcessId = Injector::WaitForProcessFullyLoaded(targetProcessName, true);

    if (targetProcessId == 0) {
        Log("Target process not found or not fully loaded.", true);
        return static_cast<int>(ErrorCodes::FAILED_TO_OPEN_PROCESS);
    }

    ErrorCodes result = ErrorCodes::SUCCESS;

    Sleep(5000);

    if (Injector::InjectDLL(targetProcessId, dllPath, true)) {
        Log("DLL injection successful.", true);
    }
    else {
        Log("DLL injection failed.", true);
        result = ErrorCodes::FAILED_TO_INJECT_DLL;
    }

    system("pause");

    return static_cast<int>(result);
}

Main.h:
#pragma once

#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <chrono>
#include <ctime>
#include <vector>
#include <string>
#include <algorithm>

class Injector {
public:
    static bool InjectDLL(DWORD processId, const std::wstring& dllPath, bool verbose);
    static bool GetProcessIdByName(const std::wstring& processName, DWORD& processId);
    static DWORD WaitForProcessFullyLoaded(const std::wstring& processName, bool verbose);
};
 
Последнее редактирование:
Начинающий
Статус
Оффлайн
Регистрация
3 Авг 2023
Сообщения
5
Реакции[?]
0
Поинты[?]
0
лишний код
Код:
    HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
    if (!hKernel32) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the handle of kernel32.dll in the current process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    LPTHREAD_START_ROUTINE loadLibraryAddr = reinterpret_cast<LPTHREAD_START_ROUTINE>(GetProcAddress(hKernel32, "LoadLibraryW"));
    if (!loadLibraryAddr) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the address of LoadLibraryW function. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HANDLE hRemoteThread = CreateRemoteThread(hProcess, nullptr, 0, loadLibraryAddr, dllPathAddress, 0, nullptr);
вместо этого прсото
Код:
HANDLE hRemoteThread = CreateRemoteThread(hProcess, nullptr, 0, LoadLibraryW, dllPathAddress, 0, nullptr);
 
Последнее редактирование:
Начинающий
Статус
Оффлайн
Регистрация
3 Авг 2023
Сообщения
20
Реакции[?]
2
Поинты[?]
5K
лишний код
Код:
if (!WriteProcessMemory(hProcess, dllPathAddress, dllPath.c_str(), dllPath.size() * sizeof(wchar_t), nullptr)) {
        DWORD errorCode = GetLastError();
        Log("Failed to write DLL path into the target process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
    if (!hKernel32) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the handle of kernel32.dll in the current process. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    LPTHREAD_START_ROUTINE loadLibraryAddr = reinterpret_cast<LPTHREAD_START_ROUTINE>(GetProcAddress(hKernel32, "LoadLibraryW"));
    if (!loadLibraryAddr) {
        DWORD errorCode = GetLastError();
        Log("Failed to get the address of LoadLibraryW function. Error code: " + std::to_string(errorCode), true);
        VirtualFreeEx(hProcess, dllPathAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HANDLE hRemoteThread = CreateRemoteThread(hProcess, nullptr, 0, loadLibraryAddr, dllPathAddress, 0, nullptr);
вместо этого прсото
Код:
HANDLE hRemoteThread = CreateRemoteThread(hProcess, nullptr, 0, LoadLibraryW, dllPathAddress, 0, nullptr);
How is it extra code if it shows for an error? Feel more useful to be able to see the failures instead of just guessing for them?
 
Начинающий
Статус
Оффлайн
Регистрация
3 Авг 2023
Сообщения
5
Реакции[?]
0
Поинты[?]
0
Начинающий
Статус
Оффлайн
Регистрация
3 Авг 2023
Сообщения
20
Реакции[?]
2
Поинты[?]
5K
Забаненный
Статус
Оффлайн
Регистрация
2 Фев 2021
Сообщения
453
Реакции[?]
82
Поинты[?]
3K
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Сверху Снизу