Enumerate Windows "Power Availability Requests" with undocumented CallNtPowerInformation(GetPowerRequestList..) - windows

Windows 7 introduced "Power Availability Requests". This feature allows applications to notify the OS that they require the display or whole system and therefore power management should be temporarily inhibited. The feature is documented here:
https://download.microsoft.com/download/7/E/7/7E7662CF-CBEA-470B-A97E-CE7CE0D98DC2/AvailabilityRequests.docx
The availability requests feature uses an object model and provides the functions PowerCreateRequest(), PowerSetRequest() and PowerClearRequest() to create requests, activate them and ultimately remove them. This functionality is very similar to the older SetThreadExecutionState() API available in Windows 2000 but allows multiple requests to be create per-thread and improves potential diagnostics by requiring each request to have a reason string.
The OS supplied POWERCFG.EXE utility can enumerate the current outstanding requests using the command:
POWERCFG -REQUESTS
Microsoft do not document how to enumerate requests with Windows API.
The CallNtPowerInformation() function in the SDK has been updated to support a new information level called "GetPowerRequestList". This looks very much like it could be the required API but is not documented.
Please does anyone know how to call CallNtPowerInformation(GetPowerRequestList..)?
Jim

Late answer, but, I found that it was easier to call this other function instead (since CallNtPowerInformation(GetPowerRequestList, ...) returned a not supported error):
PowerInformationWithPrivileges(GetPowerRequestList, 0, 0, bufout, 16384);
Function signature seemed to be the same, and you might have to define it and GetProcAddress from powrprof.dll yourself depending on what libs you have available.
Output format seemed to be a binary blob. If I had to guess, it's a list of int64's (even in 32-bit apps), first entry is # entries (call it x), next x entries are offsets in the blob for the real entries, which themselves are some kind of variable length blob/struct, probably correlating to each PowerRequest and/or type of request. Not complete info, but that should get other people started if they're serious about trying to make this work.
You need admin to call this function (you also need admin to call powercfg /requests, so this isn't too much of a surprise, though perhaps a shortcoming depending on your use case).

Related

Diagnosing RegisterWindowsMessage leak

We are seeing atom pool resource exhaustion on production servers of one of our applications.
Using the fantastic AtomTableMonitor tool, we've isolated the issue to creation of a huge number of atoms by the RegisterWindowsMessage call. They all have names like this:
ControlOfs030D000000000270
where the number at the end changes.
My question is: How do we figure out which process is creating these atoms?
some potential resources:
https://blogs.msdn.microsoft.com/ntdebugging/2012/01/31/identifying-global-atom-table-leaks/
Atoms that begin with "ControlOfs..." are created by Borland/Embarcadero's VCL (Visual Component Library) framework in Delphi/C++Builder. These atoms are actually in the form of "ControlOfs<HInstance><ThreadID>", where <HInstance> and <ThreadID> are in hex format (so, in your case, HInstance = 0x030D0000 = 51183616, ThreadID = 0x00000270 = 624).
There is also another atom name that is created by the VCL, in the form of "Delphi<ProcessID>", where <ProcessID> is in hex format.
This means that every instance of an app that uses the VCL creates a new unique "Delphi..." atom, and its main UI thread creates a new unique "ControlOfs..." atom (these atoms are used to store TWinControl object pointers in VCL-created HWNDs via SetProp(), for use by the VCL's FindControl() and IsDelphiHandle() utility functions). Both atoms are registered with GlobalAddAtom() at app startup, and unregistered at app shutdown with GlobalDeleteAtom(), so there is no leak.
However, in Delphi/C++Builder 6 all the way up to RADStudio XE2, there is yet another atom that uses the same "ControlOfs..." name. This atom is created with RegisterWindowMessage() (for a private RM_GetObjectInstance window message), which cannot be unregistered. So, every time an affected VCL app is run, this unique atom is created and subsequently leaked.
This was eventually fixed by Embarcadero in RADStudio XE3 in 2012 (Andreas Hausladen posted a patch for earlier VCL versions). But pre-existing apps that are compiled with older versions of the VCL are affected, and there is nothing you can do to stop them from leaking without patching them to use a static name with RegisterWindowMessage().
So, to answer your question, using a combination of AtomTableMonitor and Task Manager, you should be able to figure out which apps you are running are VCL apps, and then you can check them individually for leaking atoms. Or, use SysInternals Process Monitor with a Thread Create filter to get a list of thread IDs and their creating processes over time, then you can match up those thread IDs to the leaked atom names.
You can use a tool like API Monitor and set it up to track only RegisterWindowsMessage. It will show you which process is using this function and a stack trace too (though probably not too useful without symbols).
Also, a quick Google search for ControlOfs finds https://forums.embarcadero.com/thread.jspa?threadID=47678 which matches your issue. They say it's a bug in VCL. Someone posted this fix pack if you have the code:
http://andy.jgknet.de/blog/bugfix-units/vclfixpack-10/
If you don't have the code, I suggest you look for Delphi/VCL applications in your production server and try to update them or report the issue.

How to prevent my process from CreateToolhelp32Snapshot?

Is there a way to prevent another process from detecting my process by using CreateToolhelp32Snapshot?
If you are in a environment where you need to protect users from themselves then these users need to be non-admin users and you can simply create a service or task that runs as a different user so it cannot be killed.
If you absolutely need to hide the process and your chosen method is injection & hooking then there are at least 6 things you need to hook in user-mode:
The toolhelp API
The NT4 process API in psapi.dll
The undocumented native NT API
The terminal server API
Performance counters
WMI
A "better" solution is to remove your process from the PsActiveProcessHead list but you need to be in kernel-mode to do that and that means writing a custom driver. If you go down this route your program will be labeled as malware/rootkit by some security tools (and rightly so).

How do I implement CloudPort side logic? JScript or VBScript produce an ActiveX control fault (even when left dummy, with empty-body functions)

The team I am working with has bought a CloudPort license (from CrossCheck Networks) and we are currently facing the problem of not being able to implement any sort of logic in the service Mocks (to control response selection). It would be something as simple as:
if (requestCounter++ == 1)
then
response = $fn:Global(MyFirstXmlString)$ // <-- this is CloudP syntax for vrbls
else
response = $fn:Global(MySecondXmlString)$.
We did not find any sample for using the Dll Plugin and neither of the two JScript and VBScript Tasks are working (i.e., our client machine gets back not the desired MySecondXmlString response but instead a Fault with
<faultstring>
ActiveX control '0e59f1d5-1fbe-11d0-8ff2-00a0d10038bc' cannot be instantiated
because the current thread is not in a single-threaded apartment.
</faultstring>.
Believe it or not, the fault above is being obtained even if the J- or VB-Script task is left empty! It's hard for us to believe that all the logic functionality advertised in the CloudPort UI is fake and that nothing is able to help one implement the kind of logic described above.
Any help would be appreciated!
Thanks,
Pompi
PS: A bit more details here on why the kind of logic described above is needed: We use SoapSonar in our testing framework to fire requests to a BizTalk orchestration application. The CP mocks are needed to simulate the environment of that BT orchestration. We cannot control individual mocked responses via SSonar requests: the (for cloudport: incoming) client requests are made by Production code and cannot be altered or controled by our SSonar client). The only Tasks functionality that worked for us is a DB-table working as an offline channel b/w SSonar and CP (SSonar writes in it and CP reads from it). CloudPort's reading of, say, responseXml's, from DB works fine but we cannot find a way to implement further behavior controlling logic on the CP side. Therefore, this stackoverflow posting. And thx for having the patience to read this whole shananigan :).
Don't think you can control this from the script.
The threading model should be controlled by the host, which I suppose uses windows's "vbscript.dll" for the actual execution.
So if you cannot find any settings under the tool's options or in the help :), you should look in the registry keys for the threading options of that ActiveX or "vbscript.dll"
That is the "ThreadingModel" value and try to change the values (you will also have to search the net for those, don't know them by heart).
There are chances that some other application (antivirus?) has changes the path to the dll that the COM interface should actually point to (see http://social.technet.microsoft.com/Forums/en-US/ieitpropriorver/thread/ac10bd5f-6d91-4aac-857c-0ed5758088ec)
Hope it helps.

Two-way communication between kernel-mode driver and user-mode application?

I need a two-way communication between a kernel-mode WFP driver and a user-mode application. The driver initiates the communication by passing a URL to the application which then does a categorization of that URL (Entertainment, News, Adult, etc.) and passes that category back to the driver. The driver needs to know the category in the filter function because it may block certain web pages based on that information. I had a thread in the application that was making an I/O request that the driver would complete with the URL and a GUID, and then the application would write the category into the registry under that GUID where the driver would pick it up. Unfortunately, as the driver verifier pointed out, this is unstable because the Zw registry functions have to run at PASSIVE_LEVEL. I was thinking about trying the same thing with mapped memory buffers, but I’m not sure what the interrupt requirements are for that. Also, I thought about lowering the interrupt level before the registry function calls, but I don't know what the side effects of that are.
You just need to have two different kinds of I/O request.
If you're using DeviceIoControl to retrieve the URLs (I think this would be the most suitable method) this is as simple as adding a second I/O control code.
If you're using ReadFile or equivalent, things would normally get a bit messier, but as it happens in this specific case you only have two kinds of operations, one of which is a read (driver->application) and the other of which is a write (application->driver). So you could just use WriteFile to send the reply, including of course the GUID so that the driver can match up your reply to the right query.
Another approach (more similar to your original one) would be to use a shared memory buffer. See this answer for more details. The problem with that idea is that you would either need to use a spinlock (at the cost of system performance and power consumption, and of course not being able to work on a single-core system) or to poll (which is both inefficient and not really suitable for time-sensitive operations).
There is nothing unstable about PASSIVE_LEVEL. Access to registry must be at PASSIVE_LEVEL so it's not possible directly if driver is running at higher IRQL. You can do it by offloading to work item, though. Lowering the IRQL is usually not recommended as it contradicts the OS intentions.
Your protocol indeed sounds somewhat cumbersome and doing a direct app-driver communication is probably preferable. You can find useful information about this here: http://msdn.microsoft.com/en-us/library/windows/hardware/ff554436(v=vs.85).aspx
Since the callouts are at DISPATCH, your processing has to be done either in a worker thread or a DPC, which will allow you to use ZwXXX. You should into inverted callbacks for communication purposes, there's a good document on OSR.
I've just started poking around WFP but it looks like even in the samples that they provide, Microsoft reinject the packets. I haven't looked into it that closely but it seems that they drop the packet and re-inject whenever processed. That would be enough for your use mode engine to make the decision. You should also limit the packet capture to a specific port (80 in your case) so that you don't do extra processing that you don't need.

GetThreadId on pre-vista systems?

Apperantly, GetThreadId is a Vista API. How can I get a thread's id on pre vista systems?
There are a few options:
When you call CreateThread, you get the handle back.
You can call GetCurrentThreadId to get the current thread's ID.
You can use Thread32First/Thread32Next to enumerate threads.
If you can somehow make the thread in question call GetCurrentThreadId and store it somewhere, you could read the result.
If the thread in question enters an alertable wait state frequently, you could send it an APC with QueueUserAPC; the APC handler can then call GetCurrentThreadId and communicate the result back to the caller using whatever method you like.
You can also do this with undocumented NT functions. Using NtQueryInformationThread() on the ThreadBasicInformation class will give you the thread ID in the returned structure. An example can be found in the wine source. However, I'm not sure what versions of windows this is available on - keep in mind these undocumented functions can change at any time, so it's best to test them on the older versions of windows you're interested in, and simply use GetThreadId() where it's available.
Note that these undocumented functions can only be accessed by LoadLibrary() and GetProcAddress() on NTDLL; they have no import library. According to MSDN, declarations for the data structures can be found in Winternl.h, but if not, just define them yourselves based on the ntinternals links above.

Resources