Injecting/Executing Code in a processes Main Thread.... how to??

hey guys!

Long time no talk! Honestly didnt know I was still paying for this account lol Might as well use it!

Ok guys, So Im working with a few languages, But I have a personal goal to make a C++/C# UDF(Include) for Autoit that can do all of the C++ functions and such,. ive done pretty well so far .. injecting and executing my own code into my own thread etc. BUT im stuck on something so heres my question...

Im trying to Inject and Execute ASM (converted to OPCodes) into a extrernal processes Main thread then execute the code.. Like I said before Im able to do this in my own thread but the task im trying to do must be executed in the main thread of the process since the process has some sort of check stopping me from executing some functions in my own thread..

So first off im running WinXP not lower..

Second, I need some sort of example please in functions, (DLL Functions that can be called if possible.. Kernel32.dll, user32 etc)

Heres exactly what I need to do..

1. I need to be able to get the handle of the processes Main thread
2. Suspend the main thread (SuspendThread -->Kernel32.dll)
3. Allocate memory (VirtualAllocEx)
4. Inject the ASM
5. Execute the code
6. ??
7. Resume the main thread (ResumeThread) **WITHOUT CRASHING THE APP!* xp

This is a personal project im working on for learning purposes and for the debugging/enhancement of my own apps.

Thank you to who ever can help me.

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Why you don't change OEP, store real OEP in somewhere, add new section, change OEP to your section, then jump back to real OEP?

Why you don't use DLL injection? Inject you DLL, do whatever you want then let thread resume...
jay1996Author Commented:
I dont want to inject a dll...

what I need to do is get access to the external processes main thread,Suspend it, then inject my code then execute.. then resume.

could someone help me out please?
how about OEP method?
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

jay1996Author Commented:
OEP as in Original entry point... How will this help me access the external processes main thread?

I need to find the External processes Main thread handle #1

Example... My_app1.exe --> Finds Main Thread Handle of live process (this_app2.exe)
So I need code in my_app1.exe to access this_app2.exe's Main thread, Suspend it, inject my code into this_app2.exe's main thread, Execute it, then Resume this_app2.exe's Main thread. This way I can call ALL of this_app2.exe's functions with my injected code.

hope you can help..
You can create new section in your exe (before running it) with any size you need, then write your special code in your own section, then change your OEP to point your new section, run your code and then jmp back to your old OEP. Method of infecting exe files that virus and worms use.

There is a lot of articles about how to inject DLL into exe (not in run-time, injecting DLL and for example making EXE password protected with injected DLL, see:

How about this solution?

Because modifying running remote exe's main thread, executing your code and resuming thread will be really time consuming and hard point to achieve... But let me know if you SHOULD use your own method, I'll try to find a way for it.
jay1996Author Commented:
I need to be able to Inject/Execute code into the processes main thread 'on the fly' So when I want a function called that cant be called in my own thread, I just want to click a button on my app, to call the function, Not inject at runtime and let it execute thats not what im trying to do. heres some of my code that uses my own thread. and its 'On the fly' injecting so I just click the inject button and its done.

The code below is the function that is called when the button 'Inject' is clicked, I need this EXACT ASM to be injected and executed into the processes main thread when I click the button. I have the functions for suspending and resuming, I just need to know how to get the Main Thread Handle of the external process and be able to inject/execute the code into it. Ive seen this done so many times its ridiculous, but the people ive seen do it, are for personal projects with no sharing :(. Please help MY situation please hear me out.

Func InjectCode()
	Global $hProcess = _WinAPI_OpenProcess(BitOR($PROCESS_CREATE_THREAD, $PROCESS_VM_OPERATION, $PROCESS_VM_WRITE),False,ProcessExists("Wow.exe"))
	;DataBuffer Struct to Store the Lua String
	Global $LuaEnt = GUICtrlRead($LString)
	$DataBuffer = DllStructCreate("char LuaString[" & StringLen($LuaEnt) + 1 & "]")
	DllStructSetData($DataBuffer, "LuaString", GUICtrlRead($LString))
	;Allocate the memory for the DataBuffer..
	$RemoteData = _MemVirtualAllocEx($hProcess, 0, sizeof($DataBuffer), $MEM_COMMIT, $PAGE_READWRITE)
	;Struct to hold the actual ASM Code.
	$CodeBuffer = DllStructCreate("byte[58]")
	;allocate eaxct memory for asm to be called
	$RemoteCode = _MemVirtualAllocEx($hProcess, 0, sizeof($CodeBuffer), $MEM_COMMIT, $PAGE_EXECUTE_READWRITE)
	;Lua_DoString_Inject - MOV EAX,49AAB0 ASM::B8B0AA4900
	DllStructSetData($CodeBuffer, 1, _
			"0x" & _;                        <---CurMgr Updare Start--->
			"C7C2809F1301" & _;                      mov EDX, 01139F80
			"8B92342C0000" & _;                      mov EDX, [EDX+0x2C34]
			"648B052C000000" & _;                    mov eax, DWORD PTR FS:[0x2C]
			"8B00" & _;                              mov EAX, [EAX]
			"83C010" & _;                            add EAX, 0x10
			"6A00" & _;                      <---CurMgr Updare End Lua_DOString Start--->
			"68" & SwapEndian($RemoteData + (_ptr($DataBuffer, "LuaString") - _ptr($DataBuffer))) & _
			"68" & SwapEndian($RemoteData + (_ptr($DataBuffer, "LuaString") - _ptr($DataBuffer))) & _
			"B8B0AA4900" & _;                        MOV EAX,49AAB0
			"FFD0" & _;                              CALL EAX
			"83C40C" & _;                            ADD ESP,C
	;Inject ASM and String Struct
	Local $written
	_WinAPI_WriteProcessMemory($hProcess, $RemoteCode, _ptr($CodeBuffer), sizeof($CodeBuffer), $written)
	_WinAPI_WriteProcessMemory($hProcess, $RemoteData, _ptr($DataBuffer), sizeof($DataBuffer), $written)
	; Create thread in the target process. The start address is of course our injected code
	$call = DllCall("Kernel32.dll", "int", "CreateRemoteThread", "ptr", $hProcess, "ptr", 0, "int", 0, "ptr", $RemoteCode, "ptr", 0, "int", 0, "dword*", 0)
	$hThread = $call[0]
	; We're polite guests so we clean up after ourselves.
	_MemVirtualFreeEx($hProcess, $RemoteCode, sizeof($CodeBuffer), $MEM_RELEASE)
	; Get the return value and return. Mission Successful
	$call = DllCall("Kernel32.dll", "ptr", "GetExitCodeThread", "ptr", $hThread, "dword*", 0)
;~ 	_ResumeThread($WoWThread)
	Return $call[2]

Open in new window

evilrixSenior Software Engineer (Avast)Commented:
Maybe the Microsoft detours library will assist you?

Detours is a library for instrumenting arbitrary Win32 functions on x86, x64, and IA64 machines. Detours intercepts Win32 functions by re-writing the in-memory code for target functions. The Detours package also contains utilities to attach arbitrary DLLs and data segments (called payloads) to any Win32 binary.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jay1996Author Commented:
No one can give me a code template that gets access to a live processes main thread, suspends it, injects code into it , executes it then resumes..? please worth fat 500 points
evilrixSenior Software Engineer (Avast)Commented:
Did you look at Detours? It lets you hook into Win32 API functions, hijack them, run your own code and then (if you still want to) run the original API function called. Does this not provide you with a mechanism for doing what you are after?
jay1996Author Commented:
How about doing it with these kernel32 functions to access main thread then inject/execute?


Ill look into the detours dll.. Do you know if its made in .Net? because I cant call functions from a .Net DLL in autoit :(
evilrixSenior Software Engineer (Avast)Commented:
>> Do you know if its made in .Net?
It's designed to hook win32 API functions so I'm pretty sure it's a native C++ API.
jay1996Author Commented:
blah, Never ended up even using detours, I figured out how to hook endscene and reroute it to execute my code. Thanks anyway
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.