I've already saw many tutorials and articles about hooking, yet I don't quite understand it. Mainly because every single example uses different solution.
I know I will have to implement something that will keep the hook alive. Usually it's some kind of while cycle. Q1: If this loop was in some class with callbacks, will it prevent the thread from executing them?
I know it will take a while, but I would highly appreciate some well explained example of global keyboard hook. Or simply link me to some working example with binaries. (Trust me, I've been trying to google it last few hours).
Thank you
I know I will have to implement something that will keep the hook alive
No, that's not a concern. A global hook requires a DLL with the callback. That DLL gets injected in all running processes. It will stay loaded in the process until you call UnHookWindowsHookEx() or the process terminates, whichever comes first.
Do note that you can also hook the keyboard with WH_KEYBOARD_LL. That's not a global hook, Windows will switch context to your program and make the callback. It is much easier to use since you don't need an IPC mechanism with the injected DLL that the global hook requires. The low level hook stays active until you unhook, the thread that owns the message queue terminates or your process terminates, whichever comes first.
There's a skeletal keyboard hook with downloadable code on my web site here (note the "download" button at the bottom of the page). The article discusses some things you need to understand like shared sections, and informs you of Kyle Marsh's excellent article on Win32 hooks (if some idiot at MSDN hasn't taken it down by now, for being insufficiently .netty).
The source code is in the example, it just needs a makefile/sln building for it (I don't know what compiler/version you'll be using). Code spookily similar to that has been in a shipping commercial product for a decade, so I know it works.
Note that integrity level issues can reduce the utility of hooking in Vista and W7.
your program will need to stay alive during the hook. Your program is the one that calls SetWindowsHookEx / UnSetWindowsHookEx (or whatever it's called). Between those calls, you will indeed have a message loop (this is probably the while loop you're talking about) just like any typical windows program.
But because your program is a different process than the ones you're hooking, your message loop will not cause other processes to hang. It's called multitasking :)
Related
I want know what are the possible solutions to bypass a dll injection made by a rootkit everytime that any process is executed (where is used a global hook on WH_CALLWNDPROC message to detect this)?
Based in my case and also in this answer, i already know (and tested) of two alternatives that works 100% to bypass this, are they::
1. UnhookWindowsHookEx
2. Execute my process via other process, with flag DEBUG_ONLY_THIS_PROCESS using CreateProcess, to receive notifications of DLL loading, when this is detected i take the EntryPoint of dll and write something to that, then the dll is unloaded.
3. Other possible solution could be TLS callback like was said on answer linked above, but i don't know how implement (in code) to this purpose of anti dll injection. Someone know and could give a code example?
Thank you in advance by any suggestion/or others alternatives to bypass this way of dll injection.
EDITION:
I think that the 3rd possible solution enumerated above seems deserve
a attention. Then I'm searching by a answer with a code example about this: "A process can host a TLS callback, and then it will receive notifications of thread creation. That can intercept thread creation such as what is produced by CreateRemoteThread. If the thread start address is LoadLibrary(), then you have a good indication that someone is about to force-load a DLL." And then block the dll injection.
I think it's unnecessary to keep finding different alternatives, instead, use the alternatives you have already found, such as UnhookWindowsHookEx. If you want, just try out the TLS callback anyway.
A while back I made a post regarding creating a dll, for the purpose of injection, that will cause the host application to trigger an Nvidia Optimus laptop to "awaken" the dGpu. This being necessary because of the pathetic system nvidia created here which results in MANY applications not recognizing the presence of the power dGpu, and instead using the integrated intel gpu. (Specifically some video processing apps which take hours longer using Intel's than it would Nvidia's). That post was here.
Suffice to say, I moved to work in Antarctica and gave up on the project. I just picked it back up years later and decided to learn (enough) C++ to program it here. I have created the DLL, and if I place the DX code in a function, then call that function from a host "caller" program.. IT WORKS!!! However, if I put that code in the DLLMAIN, and then simply load that dll from my "caller" program (without actually calling a specific function)... the procedure executes!!! However, when it gets to the part of the code where CREATEDEVICE is run, it crashes. I have since learned this is due to an issue called deadlock, or loaderlock.. i'm not sure which. I understand the concept, but don't have anywhere NEAR the C++ understanding to develop a workaround.
So basically.. can I run my procedure in DLLMAIN using some workaround? Maybe spawning an independent thread somehow (so DLLMAIN can finish executing to it's return?) Thanks for any info. I'll include the vcproject source code here.. but it's a Frankenstein of things I found online.. so don't look for elegance- I know next to nothing about C++ programming! http://s000.tinyupload.com/index.php?file_id=07876333208461296171
The loader lock is a lock which is per-process and owned just after you call LoadLibrary, until just before the LoadLibrary returns. It is intended to ensure the process correctly accounts for the loaded DLLs and their order.
There is very little code which can be added in DllMain which doesn't run the risk of a fail, as any Windows call which may cause IPC can fall fowl of the loader-lock.
If you can create a thread from outside the process, or create a second function you can call directly, then this will be a better solution
I will sketch the scenario I would like to get working below.
I have one main application.
That application, based on user interactions, can load other applications inside a secure environment/shell. This means these child applications cannot interact with the OS anymore, nor with each other.
The parent program can at any time call functions of these child programs.
The child program can at any time call functions of these parent programs.
Does anyone know how to implement this in C++? Preferably both parent and child should be written in C++.
The performance of loading the child applications inside the parent application doesn't matter. The only thing that matters is the performance of the communication between child and parent when calling functions of each other.
You will have to write your own compiler.
Consider: No normal OS supports what you want. You want both executables to run inside a single process, yet that process may or may not make OS calls depending on some weirdness inside the process which the OS doesn't understand at all.
This is no longer a problem with your custom compiler, as it simply will not create the offending instructions. It's similar to Java and .Net, which also prevent such OS calls outside their control.
A portable solution: Google Native Client
One possible Linux solution:
Make AppArmor profile with "hats" (a "hat" is a sandboxing configuration to which the application can switch programmatically with libapparmor),
have the main application create a "pipe",
have the main application "fork",
change into a "hat" corresponding to the child application,
"exec" the child application,
the main application and the child application communicate via the "pipe" created earlier.
If you want a (semi)crossplatform way to do this you can use RPC to call functions in another process. It's going to work on anything that supports the distributed computing environment. It's been around for some time and the msdn documentation states that parts of windows use it for inter process communication so it's probably fast enough. Here's a tutorial on msdn that should get you up and running http://msdn.microsoft.com/en-us/library/windows/desktop/aa379010.aspx The bad part is that I haven't been able to find a tutorial about using it on linux.
If you don't want to use RPC or find it too hard to find good documentation on the subject, you can use the standard IPC(Inter Process Communication) mechanisms from unix systems to signal your process that should call a certain function. I'd recommend a message queue because it's very fast and lightweight. You can find a tutorial here: http://www.cs.cf.ac.uk/Dave/C/node25.html
I am not familiar with OS restrictions in above answers. However, I found an easy way to solve this problem. I hope it helps and does not have a technical issue. I used Linux OS. Suppose I want to call C++ program B inside another C++ program A. I wrote a perl script (such as PerlScript.pl) that contains a system call to run program B. Then in A, I did a system call like system("perl PerlScript.pl") that ask perl to run B for me.
When making a program with Qt, we can have long recursive process,
If so, after a while, windows show the "Dont answer" message next to the window title.
This message could lead the user to think the program don't work which is not true.
How can I do to avoid this message in Qt?
In order to remain responsive to the system and user input, put a long running task into its own thread. You might also want to provide feedback to the user, like a progress bar, so he sees the program is still doing some job he requested.
See also Threading Basics for an introduction on using threads with Qt and Threading and Concurrent Programming Examples for some examples.
If your process takes a long time because of loops (or recursive functions), you can call QCoreApplication::processEvents() in your loop to ask your application to treat events.
If you have only one instruction that take a long time (such as copy a large file), you may use QThread or QtConcurrent.
While Olaf's answer is good, a simpler approach would be to sprinkle QCoreApplication::processEvents() in your code.
From the docs:
Processes all pending events for the calling thread according to the
specified flags until there are no more events to process. You can
call this function occasionally when your program is busy performing a
long operation (e.g. copying a file).
I have some doubts about anti dll injection in C++.
I have a game C++ based, Im having problems with hackers with dll injection.
Then i need to prevent it.
I find notify hook there from there:
MSDN - Notification Hooks
But i dont have idea how to use it.
Its is possible notify hook to prevent dll injection?
How its possible? (With and example better).
Can be from dll? (With example better).
Thanks for read that post.
PS: sorry for my english.
Forget it, unless you do very sophisticated things, it's not going to work. By sophisticated I mean something like the code obfuscation, anti-debugging technology used in Skype. Just look at this talk.
You can spend a ton of time on trying to prevent DLL injection, in the end somebody will spend less time than you and circumvent your protection. I think the time would be better invested in an architecture that's more secure and tamperproof (ie calculating scores on the server, etc).
It's a cat and mouse game you can't win.
This question is old but I will briefly answer it in better form for anyone who does happen to stumble upon it magically after a proper response.
You cannot fully prevent code injection from within your own process, but you can try to do some tricks without interception of other processes. It is not recommended because you need to have experience and knowledge with lower-level tasks, especially to get it working properly and not prevent functionality of your own software, however...
Asynchronous Procedure Calls (APC) is an implementation from the Windows Kernel. It is primarily used for code injection into other running processes, Windows uses it a lot itself for a variety of things such as notifications being sent to specific processes. When a user-mode process calls QueueUserApc (KERNEL32), NtQueueApcThread (NTDLL) will be invoked. NtQueueApcThread (NTDLL) will perform a system call which will cause NtQueueApcThread (NTOSKRNL) to be invoked, which is not exported by NTOSKRNL - for anyone wondering, NTOSKRNL is the Windows Kernel, and a system-call is nothing more than a transition from user-mode to kernel-mode since the Native API System Routines exist in kernel-mode memory, NTDLL routines for NTAPI are system call stubs which direct control up to the Windows Kernel. When NtQueueApcThread (NTOSKRNL) is called, it'll use KeInitializeApc and KeInsertQueueApc (both do happen to be exported by NTOSKNL). When the APC is actually issued to the targeted process, KiUserApcDispatcher (NTDLL) will be locally called within the process, unless the APC is performed in a more extensive manner to bypass this activity (99% of the time it will not be prevented). This means that you have an oppertunity to intercept this behavior and prevent APC injection into your own process with one single local hook in your own process, via byte-patching (also known as "inline hooking") KiUserApcDispatcher, exported by NTDLL. The only problem which you will face is that it is undocumented and this is not officially supported by Microsoft; you'll need to figure out how the parameters work and how to prevent the callback routine from blocking off genuine requests which are needed to provide functionality for your own software. This will however include prevention of kernel-mode APC injection, not just user-mode attacks.
There are many ways to inject code into a process, and APC is simply one of them. Another common method would be through remote thread creation. When a user-mode process attacks another process via remote thread creation, it'll typically call CreateRemoteThread (KERNEL32). This will lead down to RtlCreateUserThread (NTDLL), and RtlCreateUserThread will call NtCreateThreadEx (NTDLL). NTDLL will perform a system call and then NtCreateThreadEx (non-exported routine from the Windows Kernel) will be invoked in kernel-mode memory. In the end, the targeted process will have LdrInitializeThunk locally invoked, and RtlUserThreadStart will also be invoked locally. Both of these routines are exported by NTDLL. This is a same scenario as with APC... You can patch LdrInitializeThunk locally, however you must do it properly to prevent genuine functionality within your own software.
These two techniques are not full-proof, there is no "full-proof" solution. There are many ways to inject code into a process, and there are very sophisticated methods to bypass said solutions from myself. Anti-Virus software has been battling anti-RCE/self-protection for as long as I can remember, as has Anti-Cheat systems. You should look into kernel-mode device driver development as well, it'll allow you to register kernel-mode callbacks which can help you out.
The first callback you should look into is ObRegisterCallbacks. It allows you to receive a Pre-operation callback notification whenever NtOpenProcess is called from the Windows Kernel. This means that user-mode processes will also trigger it, since NtOpenProcess ends up being called in kernel-mode after NTDLL makes the system-call. I cannot remember specifically if the callback APIs are triggered in the NtOpenProcess stub itself or if it goes deeper into Ob* kernel-mode only routines, but you can check at ease with WinDbg with remote kernel debugging, or Interactive Disassembler (target ntoskrnl.exe and use the symbolic links provided by Microsoft). ObRegisterCallbacks supports notifications for both handle creation & duplication for the process and the processes' threads, you can strip access rights you don't want permitted for the requested handle.
The second callback you should look into would be PsSetCreateThreadNotifyRoutineEx. This callback routine will allow you to receive a notification whenever a new thread creation occurs on the system; you can filter it out for your own process and if a rogue thread is created, terminate the thread.
The third callback you should look into would be PsSetLoadImageNotifyRoutineEx. This callback will provide a notification whenever a new module is loaded into a process; once again, you can filter for your own process. If you detect a rogue module, you can attempt to have your process call LdrUnloadDll (NTDLL) targeting the base address of the newly loaded image, however the reference count for the module needs to be 0 for it to be unloaded. In that case, you can try "hacky" methods like calling NtUnmapViewOfSection/NtFreeVirtualMemory. Bear in mind, if you mess up the rogue loaded module and it has set memory byte patches to redirect execution flow to its own routines, unless you restore them, your process will crash when they are referenced.
These are some ideas, commonly the ones typically used. Kernel-Mode callbacks are very popular among security software and anti-cheat software. As for thread creation, you'll be interested in mitigating this as much as possible -> if you only look for rogue DLL loads then you'll miss out on reflective DLL loading. Also remember of the other code injection methods, like thread hijacking, shared window memory exploitation with ROP chain call exploitation, DLL patching on-disk, etc.