Is KillTimer really necessary? - winapi

This may seem to be a duplicate question for Is KillTimer necessary?, but i would like to confirm this with credible source.
Does destroying window really free the resource allocated by the OS for the timer? (does DestroyWindowsTimers really get called let alone if such function actually exists? if so, where?)

No, it is not necessary. From the documentation of DestroyWindow (with emphasis added):
The function sends WM_DESTROY and WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus from it. The function also destroys the window's menu, flushes the thread message queue, destroys timers, removes clipboard ownership, and breaks the clipboard viewer chain (if the window is at the top of the viewer chain).

Doing a google search the only actual real looking reference to it looked to be some Win2k source code. The url ended with /Censorship/win2k_sources/private/.../timers.c, I'm assuming from the source code leak a while back. I did not look at the code, nor will I post a link here.
That function most likely exist - something like that almost has to exist for timers linked to window handles - since the timer message is delivered to a specific window handle.
I can't see anywhere in the documentation that states that you don't have to call KillTimer to get rid of a timer. So based on the documented contract, you need to call KillTimer. In practice Windows will probably clean it up for you, but since that is undocumented behavior you should write your code to follow the documented behavior and call KillTimer on all your timers.

Related

How to not display a UI?

MSDN at this link states that there is a flag
CMIC_MASK_FLAG_NO_UI
The system is prevented from displaying user interface elements (for example, error messages) while carrying out a command.
However, it also indicates that the structure has
nShow
Type: int
A set of SW_ values to pass to the ShowWindow function if the command displays a window or starts an application.
which I think contradicts each other as there is no indication I can set the latter parameter to 0 and there is no SW_NOSHOW parameter in the ShowWindow documentation.
Is it even possible to suppress that window? If yes - how?
TIA!!
There is some ambiguity about which UI we are talking about here.
There are UI things related to invoking the command (asking for network share password, error message on failure etc.) and CMIC_MASK_FLAG_NO_UI certainly applies here. I don't know how relevant nShow is though. The caller does not know which UI might be displayed and it makes zero sense for the callee to allow its error MessageBox to be maximized etc. Respecting SW_HIDE might end up stuck waiting for the user to interact with a window they can't see.
The other UI is actually the thing that is executed. In the cases where a new process is started we are looking at a ShellExecuteEx call. CMIC_MASK_FLAG_NO_UI is passed on as SEE_MASK_FLAG_NO_UI (same integral value) and MSDN just says "Do not display an error message box if an error occurs" for this flag. Here however, nShow is relevant and can trickle all the way down to CreateProcess.
This is how I personally deal with this situation:
Set CMIC_MASK_FLAG_NO_UI if you are going to display your own error UI in case of failures or if you are running in a silent/automated mode of execution.
Only set nShow to something other than SW_SHOW when you control the action being executed. For example, you know cmd.exe is getting called and you need to hide the console window with SW_HIDE.
It is important to remember that CMINVOKECOMMANDINFO is parsed by the default IContextMenu shell32 implementations for various shell objects (files, control panel etc.) and by 3rd-party context menu handlers. You cannot assume that they are going to respect your wishes.

Is there any way to determine if a program uses a specific Windows API functions?

Ok, it may be a bit difficult to explain:
Suppose someone creates a Windows application (using C# or any other language) that uses the GetDesktopWindow() function on the user32.dll to capture a Screenshot and then sends this image to any online service.
Since it's custom made application, no anti-virus software will be able to determine that it's a virus because it's still an unknown application for it. Also, there are legitimate uses for such API, so it's not necessarily a virus, it can be a harmless window capture tool or some kind of espionage tool.
What I want to know is: Is there any way to see what a specific EXE file does regarding the Windows functions? Can I know if "myapp.exe" uses GetDesktopWindow() of user32.dll?
This is only one example. There are plenty other Windows endpoints that I would like to know when they're used by any application.
Is there a way to do that?
It depends to what lengths you want to go doing that. It's essentially a game of cat and mouse - bad actors will attempt to find new ways to circumvent your detection by jumping through some obscure hoops, you will add more sophisticated detection methods for those tricks, they will think of new tricks, and so on.
Also, it depends on whether you want to statically or dynamically determine that, and whether you actually want to know if GetDesktopWindow is called or if "the program gets a handle to the desktop window" (which can be achieved in other ways as well).
Here is a non-exhaustive list of ideas:
You could statically determine whether the function is imported by looking at the import directory. Research the PE file structure to find out more. This article may help.
This method of detection can be easily circumvented by dynamically importing the function using LoadLibrary and GetProcAddress.
You could scan the file for the string GetDesktopWindow to detect possible usage for dynamic import.
This method of detection can be easily circumvented by packing, encrypting or otherwise obfuscating the name of the dynamically imported function.
You could dynamically observe whether the GetDesktopWindow function gets called by registering an AppInit_DLL or a global hook which is injected into every new process and hook the GetDesktopWindow function from inside the process by overwriting its first bytes with a jump to your own code, notifying your detection component somehow, executing the original bytes and jumping back. (Microsoft Detours can help there.)
This method of detection can be circumvented if the target notices the hook and removes it before calling, since its in its own process space. (You could also do some tricks with acting like a debugger and setting a hardware breakpoint on the first instruction of GetDesktopWindow, but yet again there would be ways to detect or circumvent that since the target could also modify the debug registers.)
You could build a driver that does this from kernel-mode instead, but now we are getting really deep.
Note that until now we focused on the actual GetDesktopWindow function from user32.dll. But what if the target will just use a different way to achieve its goal of getting a desktop window handle?
The desktop window handle for the current thread is stored in the TIB (thread information block) which is accessible via fs:[18] from user mode. You can see this in the GetDesktopWindow source code of ReactOS which is pretty accurate compared to Microsoft's actual implementation (which you can verify by looking at it in a debugger). The target could therefore just access the TIB and extract this value, without even calling GetDesktopWindow at all.
The target could just take a known top-level window such as the shell's hidden compatibility window which you'll get via GetShellWindow() or - to avoid detection of GetShellWindow too - for example FindWindow(NULL, "Program Manager") (or even a newly created window!) and call GetAncestor(hWnd, GA_PARENT) on it to get the desktop window handle.
I'm sure, with some creativity, your adversaries will come up with more clever ideas than these.
Also, if we take this one step further and take a look at the ultimate goal of taking a screenshot, there as well exist other ways to achieve that. First example coming to mind: They could use keybd_event to emulate pressing the PrnSc key and then read the screenshot out of the clipboard data.
So it's all a matter of how far you want to take this.
By the way, you may find the drltrace project interesting - it is a library call tracer.

Editing waveform audio input before it reaches a application

I am working on a voice changer that is supposed to manipulate the input buffer of a waveform-audio input device before the buffer is returned to a application.
The waveInOpen()-function gives 4 options to be notified when the buffer provided by waveInAddBuffer() has been filled.
The options are CALLBACK_EVENT, CALLBACK_FUNCTION, CALLBACK_THREAD, CALLBACK_WINDOW.
I have tried several things to to get my waveform manipulation to work but haven't found a reliable and clean solution yet.
What worked so far was intercepting waveInAddBuffer()-calls with Detours. I am saving all WAVEHDR-pointer used by waveInAddBuffer() and each time the function is called I delay the program for a few miliseconds and search for waveform-buffers that have been filled during the delay.
This isn't reliable though because the buffer size differs for each application and therefore there isn't a delay-time that works for every application.
I would be really thankful for new ideas!
edit:
Heres the other stuff I have tried:
Most applications set multiple flags when calling waveInOpen() that actually exclude each other. So you can never be sure what callback method actually is used. (e.g.: the flags CALLBACK_EVENT | CALLBACK_FUNCTION | CALLBACK_WINDOW are all set.)
When the CALLBACK_WINDOW flag is set, I have used the SetWindowLongPtr() function to create a subclass window that received MM_WIM_DATA messages before the window of the application. Unfortunately this didn't work, my subclass window never gets called.
I have created a custom-callback function that I replace with the callback function of the application when the CALLBACK_FUNCTION flag is set.
This didn't work because my function never gets called. I guess this is because my function is defined in a DLL, outside of the address space of the application.
There were several other things I have tried that didn't work because I made attempts that never could have worked because I didn't know enough about injection and hooks. I have learned quite a lot and I cant really summarize everything I have tried, because it's not helping the cause.

::PostMessage to an invalid hWnd

I have a thread that calls ::PostMessage(hWnd, [...]); to send a message to the main thread alerting it to the results of an async operation.
However, I'm concerned that if the thread takes a particularly long time to finish its operation, the hWnd may not exist when the PostMessage is called (the user may have closed the window).
The MSDN Documentation doesn't say anything about the results if hWnd is invalid.
Do you know from experience, or other documentation, about what I can expect if hWnd is invalid?
Raymond Chen wrote about this:
http://blogs.msdn.com/b/oldnewthing/archive/2007/07/16/3885472.aspx
http://blogs.msdn.com/b/oldnewthing/archive/2007/07/17/3903614.aspx
Some choice excerpts:
It so happens that boatloads of programs (and "boatloads" is a technical term) contain bugs where they use window handles after the window has been destroyed. When a window handle is re-used, that program sends a message to the window it thinks is still there, but instead it sends the message to a completely unrelated window. This doesn't bode well for the program, and it usually doesn't bode well for the new window that received the message by mistake either.
We left off our story last time by raising the problem of programs that send messages to windows that have already been destroyed and how window handle re-use exacerbates the problem. Although this is clearly a bug in the programs that use window handles after destroying the window, the problem is so widespread that the window manager folks in Windows NT decided to take a more proactive approach.
As others have pointed out, Ramond Chen explained what happens if the HWND gets re-used by a new window. PostMessage() will succeed, it will just go to the wrong window. However, in cases where the HWND does not get re-used, PostMessage() will fail with an ERROR_INVALID_WINDOW_HANDLE (1400) error code.

Ruby Win32Api get single character non-blocking

I'm trying to write a simple game working with two threads, one thread to get input from the user, and another thread to animate some scenes. I'm able to get characters without pressing ENTER just fine, but it blocks in the animating thread until the user presses a key. Does anyone know of a way to get a character from the keyboard non-blocking?
If you're looking to checkup on a handful of specific keys, GetAsyncKeyState() can be used to poll for state. Otherwise, you should implement a message loop and handle WM_CHAR messages in your application.
You can access raw win32 functions with a library similar to the following if your environment doesn't already support the win32 functions you need.
RAA - win32-api # raa.ruby-lang.org
Here are relevant links for GetAsyncKeyState().
GetAsyncKeyState() # MSDN
Virtual-Key Codes # MSDN (used as values for GetAsyncKeyState and other functions)
If you decide to go with a message loop, you'll need to implement it on the same thread that hosts the window for your application. A short explanation is available here:
Message Loop in Microsoft Windows # Wikipedia
As shown at that link, there isn't a whole lot to a message loop. Your framework may already have one running behind the scenes to host the window containing your graphics. If this is the case, you don't need a 2nd thread for input; but you will need to intercept and handle windows messages for that host window.
If you have to implement a message loop on your own, you can use the skeleton at the wikipedia link. The DispatchMessage call will direct a windows message to the appropriate window handler. You will need to look for a matching stub or handler for windows messages in your ruby framework, and handle WM_CHAR from there.
DispatchMessage # MSDN
WM_CHAR # MSDN
If you wish to know when keys are pressed/depressed, then you will want to handle WM_KEYUP and WM_KEYDOWN messages.
WM_KEYUP # MSDN
WM_KEYDOWN # MSDN
Also note, GetAsyncKeyState() can be called and returns key state even while another application is in the foreground. Handle WM_ACTIVATE and WM_SETFOCUS/WM_KILLFOCUS messages so that your application ignores or defers checks while a different window is active if you only care about key state while your window is the primary foreground window.
WM_ACTIVATE # MSDN
WM_SETFOCUS # MSDN
WM_KILLFOCUS # MSDN
I have used rubygame for this. It gives you the ability to attach functions to keyboard events with minimal code. RubySDL and GoSu will give you similar functionality.
If you don't want to go that route with game related gems take a look at this on how to check if data is available in IO object. This could be use to poll the keyboard.

Resources