Page 1 of 1

Inject dll from DataSection.

Posted: Wed Dec 03, 2014 4:39 pm
by Cyberity
Hello !

Is possible to inject a dll from DataSection?

So like:

DataSection
MyDll : IncludeBinary "mydll.dll"
EndDataSection

InjectDLL(?MyDLL, PID)

With this procedure I can inject dll but from DataSection I can't:

Procedure InjectLibA(dwProcessId.l, pszLibFile$)
hProcess.l
hThread.l
lzLibFileRemote.l
lSize.l
endSize.l
lsThreadRtn.l

hProcess = OpenProcess_(#PROCESS_QUERY_INFORMATION | #PROCESS_CREATE_THREAD | #PROCESS_VM_OPERATION | #PROCESS_VM_WRITE, 0, dwProcessId)

If hProcess = 0 : Goto ErrHandle : EndIf
lSize = 1 + Len(pszLibFile$)
endSize = lSize

lzLibFileRemote = VirtualAllocEx_(hProcess, #Null, endSize, #MEM_COMMIT, #PAGE_READWRITE)

If lzLibFileRemote = 0 : Goto ErrHandle : EndIf

If (WriteProcessMemory_(hProcess, lzLibFileRemote, pszLibFile$, endSize, #Null) = 0) : Goto ErrHandle : EndIf

OpenLibrary(0, "Kernel32.dll") : lsThreadRtn = GetFunction(0, "LoadLibraryA") : CloseLibrary(0)

If lsThreadRtn = 0 : Goto ErrHandle : EndIf

hThread = CreateRemoteThread_(hProcess, #Null, #Null, lsThreadRtn, lzLibFileRemote, #Null, #Null)

If (hThread = 0) : Goto ErrHandle : EndIf

WaitForSingleObject_(hThread, #INFINITE)

If lzLibFileRemote<>0
VirtualFreeEx_(hProcess, lzLibFileRemote, 0, #MEM_RELEASE)
MessageRequester("Hi", "Hi", 0)
EndIf
End

ErrHandle:
CloseHandle_(hThread)
CloseHandle_(hProcess)
EndProcedure

Re: Inject dll from DataSection.

Posted: Wed Dec 03, 2014 4:43 pm
by IdeasVacuum
Why would you need this capability?

Re: Inject dll from DataSection.

Posted: Wed Dec 03, 2014 4:48 pm
by Cyberity
IdeasVacuum wrote:Why would you need this capability?
I want to make my app. to protable so everything in DataSection like pictures, sounds dlls and my program using dll injection too.

Re: Inject dll from DataSection.

Posted: Wed Dec 03, 2014 6:50 pm
by Thorium
It's possible but it's a lot of work. You cant just load a dll and expect it to run. A DLL is not just machine code. It's a complicated file format called Portable Executable in short PE.

In order to get it work you need to manualy initialize it and create a thread at the entry point, not the start of the file.
On initialization you need to load the PE sections, set memory access settings, perform relocations and initialize the import table. There is a documention of the file format on MSDN. And there is a userlib which does it in it's own process. You could take a look at the code, i think it's open. It's called MemoryModule: http://www.purebasic.fr/english/viewtop ... 27&t=44091

Re: Inject dll from DataSection.

Posted: Wed Dec 03, 2014 11:37 pm
by Mistrel
Just write it to the temp directory and load it from there.