#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tlhelp32.h>
#define USAGE "./%s <process> <fullPathDll>\n\n"

int InjectDllDansProcessus(long pidProcAInjecter , char* fullPathDll);
long NomProcessusToPid(char* process);

int main(int argc , char* argv[])
{
    printf("Hook fucking api par 0vercl0k\n\n");
    if(argc != 3){printf(USAGE,argv[0]);return 0;}
    if(InjectDllDansProcessus(NomProcessusToPid(argv[1]),argv[2]) == 1)
        printf("[*] Dll injected.\n\n");
    return 0;
}


int InjectDllDansProcessus(long pidProcAInjecter , char* fullPathDll)
{
    long tailleStringDll = strlen(fullPathDll) + 1;

    printf("[+] Ouverture du process.\n");

    HANDLE handleProcess = OpenProcess(PROCESS_ALL_ACCESS , FALSE , pidProcAInjecter);
    if(handleProcess == NULL)return 0;

    printf("[+] Reservation et écriture dans la mémoire du processus.\n");
    LPVOID addrEspaceReserve = VirtualAllocEx( handleProcess , NULL , tailleStringDll , MEM_COMMIT , PAGE_EXECUTE_READWRITE);
    if(addrEspaceReserve == NULL)
        return 0;

    int retourFonctionWrite = WriteProcessMemory( handleProcess , addrEspaceReserve , fullPathDll , tailleStringDll , 0);
    if(retourFonctionWrite == 0)
        return 0;

    printf("[+] Creation du thread dans le processus.\n");
    DWORD identificateurThread ;
    LPTHREAD_START_ROUTINE addrLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(LoadLibrary("kernel32"),"LoadLibraryA");
    HANDLE retourFonctionCreate = CreateRemoteThread( handleProcess , NULL , 0 , addrLoadLibrary , addrEspaceReserve , 0 , &identificateurThread );
    if(retourFonctionCreate == NULL)
        return 0;

    WaitForSingleObject(retourFonctionCreate,INFINITE);
    VirtualFreeEx( handleProcess , addrEspaceReserve , 0 , MEM_DECOMMIT);

    CloseHandle(handleProcess);
    CloseHandle(retourFonctionCreate);


    return 1;
}

long NomProcessusToPid(char* process)
{
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32 structprocsnapshot = {0};

    structprocsnapshot.dwSize = sizeof(PROCESSENTRY32);

    if(snapshot == INVALID_HANDLE_VALUE)return 0;
    if(Process32First(snapshot,&structprocsnapshot) == FALSE)return 0;

    while(Process32Next(snapshot,&structprocsnapshot) )
    {
       if(!strcmp(structprocsnapshot.szExeFile,process))
       {
            CloseHandle(snapshot);
            return structprocsnapshot.th32ProcessID;
       }
    }
    CloseHandle(snapshot);
    return 0;
}