Solved

SetWindowsHookEx() fails inside a thread of Windows service created using AfxBeginThread()

Posted on 2004-04-28
10
1,855 Views
Last Modified: 2013-12-03
I’ve written a piece of code that works perfectly fine inside an executable on Win 2k platform, but does not work when invoked from a multi threaded Windows Service.

The task is to track change in value of a status bar and items of a list control on a 3rd party executable. The window for this target application is first searched using EnumWindows() and than the following code is executed

g_hinstDll = LoadLibrary("hookDLL.dll");

if (g_hinstDll == NULL) {
…                  
return;
}
            
// Set WH_CALLWNDPROCRET hook on the 3rd party application thread            
g_hhook = ::SetWindowsHookEx(WH_CALLWNDPROCRET, (HOOKPROC)CallWndProcRet, g_hinstDll, m_target_threadid);

if (g_hhook == NULL) {
TRACE("Can't create hook! Error Code = %d\n",GetLastError());
return;
}

This code works perfectly when compiled as an executable. But if we run this code in a thread invoked using AfxBeginThread(), inside a Windows Service, it fails with the error code ERROR_ACCESS_DENIED after the SetWindowsHookEx call.

Q - Can somebody give some pointers on what could be the reason for the error message?

Additional Information –
•      The service has the option ‘Allow service to interact with the desktop’ option selected, to facilitate search of the target application window thread.

•      Currently logged on user is part of the Administrators group.

•      Inside this particular thread in the service, i’m able to open the target process using these calls
OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION| PROCESS_VM_WRITE, FALSE, m_target_processid)
Or
OpenProcess(STANDARD_RIGHTS_REQUIRED, FALSE, m_target_processid)

•      Call for starting the thread is
AfxBeginThread(RUNTIME_CLASS(CHookTarget),THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED, NULL)
0
Comment
Question by:__Sarge
  • 4
  • 2
  • 2
10 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 93 total points
Comment Utility
>>but does not work when invoked from a multi threaded Windows Service.

What kind of messages of would you like to hook on an invisible desktop that has no windows? See http://www.microsoft.com/msj/0398/service2.aspx ("Why Do Certain Win32 Technologies Misbehave in Windows NT Services?"):

On Windows NT 4.0, only one window station can be visible, WinSta0. The visible window station is also defined as interactive. A nonvisible window station is noninteractive. A nonvisible window station does not receive any user input and no display device is associated with it.
As stated earlier, desktops are contained within window station objects, just as a directory contains files. A desktop object contains a logical display surface and includes windows, menus, and hooks. Only desktops belonging to the visible window station can be seen and receive user input and only one desktop can be seen and receive input at a time. This desktop is known as the active desktop.
0
 

Author Comment

by:__Sarge
Comment Utility
Thanks for your comment. The article is very informative.

The application that has to be hooked is on the interactive desktop. The service thread that is trying to hook this interactive desktop application, is running under LocalSystem account, with 'Allow service to interact desktop' option selected. This allows the service thread access to the interactive desktop.

The service thread has following piece of code

g_hinstDll = LoadLibrary("hookDLL.dll");

g_hhook = ::SetWindowsHookEx(WH_CALLWNDPROCRET, (HOOKPROC)CallWndProcRet, g_hinstDll, m_target_threadid);

SetWindowsHookEx() fails with  ERROR_ACCESS_DENIED.

Could it be related to g_hinstDll handle? This module of this handle is under LocalSystem context. Is this creating a problem?

Any other idea on what could be reason for this error?

0
 
LVL 86

Expert Comment

by:jkr
Comment Utility
>>Could it be related to g_hinstDll handle?

No. It is related to the fact that you cannot hook anything from a service running on an invisible desktop.
0
 
LVL 2

Expert Comment

by:colmcc
Comment Utility
>No. It is related to the fact that you cannot hook anything from a service running on an invisible desktop.

Isn't it more accurate to say: You cannot hook anything in a thread that belongs to a desktop other than the current one?  

I imagine the ERROR_ACCESS_DENIED relates to the attempt to cross this desktop boundary.  However, threads running within the scope of the service will be receiving messages (just not WM_PAINTs), and I think these could be hooked if desired.  (Though that's not what Sarge is trying to do.)

Sarge,
'Allow service to interact desktop' does not get around the above restriction. If you need the main part of your program to run as a service, I think you will have to factor out the part that establishes the hook into a separate process. The service could create this on the interactive desktop and perhaps communicate with it via a named pipe, if necessary.

Colin.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 2

Expert Comment

by:colmcc
Comment Utility
Hi Sarge,

Well, I may have been wrong.  My apologies.  

I thought that "interactive services" still ran in a separate Window Station and desktop, and yet somehow were allowed to interact with the user.  Having looked for more information via Google, it sounds like they actually run in the interactive Window Station/desktop.  I can't find an explicit statement of this, but it's implied by various things I've seen.

I found this MS KB article relating to NT4 -
http://support.microsoft.com/default.aspx?scid=kb;EN-US;163892

So, unless Win2k has been deliberately changed to prevent this, it sounds like what you are trying ought to work.  Although, MS actually recommend the approach I mentioned above, for security reasons  -

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/localsystem_account.asp


Colin
0
 
LVL 2

Expert Comment

by:colmcc
Comment Utility
0
 

Author Comment

by:__Sarge
Comment Utility
Colin,
Thanks for all your inputs.

I have already tried launching a new process(Win32 exe) through CreateProcess() in the interactive desktop. I could see the GUI of the launched exe, but even this exe could not hook the target application. The error returned was the same  ERROR_ACCESS_DENIED.

I cannot use CreateProcessWithLogonW() as the service also needs to run on WinNT4.0. I would see if CreateProcessAsUser(), works in this case.


0
 
LVL 2

Assisted Solution

by:colmcc
colmcc earned 92 total points
Comment Utility
Hi Sarge,

Yes.  CreateProcess would still give ERROR_ACCCESS_DENIED because the user would still be LocalSystem. (Assuming that the problem is the one described in the MS KB article.)

CreateProcessAsUser sounds like a good idea.  You would need to get hold of an access token for the logged-on user, which can be a bit tricky I think.  Possibly OpenProcessToken on the hook-target process, followed by ImpersonateLoggedOnUser might do the trick.

But it is still a bit worrying that the MS KB article suggests that the problem you are seeing with the service was fixed in NT4 SP2.  Maybe there is something else going on here?

A few things you could try :

Run the service on NT4 (SP >= 2).  Do you get the same error?

Replace AfxBeginThread with the Win32 function CreateThread. (It seems unlikely, but maybe MFC is screwing things up somehow.)

If the problem really is that LocalSystem has no access to the user's desktop, perhaps it would be possible to allow this access (DF_ALLOWOTHERACCOUNTHOOK), using SetUserObjectInformation.

None of the above is particularly well thought through, but maybe it will give you a few ideas.

Good luck,
Colin.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article shows how to make a Windows 7 gadget that accepts files dropped from the Windows Explorer.  It also illustrates how to give your gadget a non-rectangular shape and how to add some nifty visual effects to text displayed in a your gadget.…
If you have ever found yourself doing a repetitive action with the mouse and keyboard, and if you have even a little programming experience, there is a good chance that you can use a text editor to whip together a sort of macro to automate the proce…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now