Click here to Skip to main content
15,510,771 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Good Afternoon

I'm trying to inject a DLL into a process but when the dll is injected the code isn't run

DLL code
C++
 #ifndef _DLLTEST_H_
 #define _DLLTEST_H_

 #include <stdio.h>
 #include <windows.h>
#include <stdlib.h>

 extern "C" __declspec(dllexport) void NumberList();


 #endif


The rest of the dll code

C++
#include "dlltest.h"
 #define MAXMODULE 50

 char module[MAXMODULE];


 extern "C" __declspec(dllexport)

 void NumberList() 
 {
	 FILE *f=fopen("C:\\asd.txt","w");
     
 }

DLL created with Visual C++ 2010


DLL injector code


C++
unsigned long GetTargetProcessIdFromProcname(char *procName)
{
   PROCESSENTRY32 pe;
   HANDLE thSnapshot;
   BOOL retval, ProcFound = 0;

   thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

   if(thSnapshot == INVALID_HANDLE_VALUE)
   {
      puts("Erro");
      return 0;
   }

   pe.dwSize = sizeof(PROCESSENTRY32);

    retval = Process32First(thSnapshot, &pe);

   while(retval)
   {
      if(strstr(pe.szExeFile, procName) )
      {
         ProcFound = 1;
         break;
      }

      retval    = Process32Next(thSnapshot,&pe);
      pe.dwSize = sizeof(PROCESSENTRY32);
  }

   return pe.th32ProcessID;
}
main()
{
	unsigned long id;
	DWORD *pid;
	HANDLE hd;
	LPVOID gp,rs;
	
	gp=(LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

	id=GetTargetProcessIdFromProcname(PROCESS_NAME);

	hd=OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);

	rs=(LPVOID)VirtualAllocEx(hd, NULL, strlen(DLL_NAME), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);

	if(!WriteProcessMemory(hd, (LPVOID)rs, DLL_NAME, strlen(DLL_NAME), NULL))
	puts("error 1");
	if(!CreateRemoteThread(hd, NULL, 0, (LPTHREAD_START_ROUTINE)gp, (LPVOID)rs, 0, NULL))
		puts("error 2");

	system("pause");

}


Need help
Posted

1 solution

DllMain is invoked when you inject the dll into the process. So you should call your code in DllMain when fdwReason is <dll_process_attach></dll_process_attach>
see DllMain Entry Point[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900