Need device independent bitmap bits - winapi

I'm building a dll in C++ to be imported into a VB project. The dll exposes a function that will extract the preview image of a specified document through the Win Shell, and then writes it into a buffer to be used by the VB app.
So far, I'm able to get the HBITMAP handle without issue. I was also able to extract the bitmap data using the GetBitmapBits function. However, this will not work as the object that requires the bit data needs it to be in a device independent format.
I've read that GetDiBits is the function to use for this purpose, but I'm having a hard time figuring out how to call the function successfully.
What device context should I be using? Also, how can I ensure that it writes out the data in device independent format?
Thanks in advance.

If your HBITMAP references a device dependent bitmap, and you need device independent bits, you have to convert them. Try creating a CImage and call the BitBlt method to put device independent bits in it.

Related

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.

Windows GDI BitBlt / MaskBlt across multiple displays on modern systems: Could there be DCs on different devices?

While spelunking in some old code of mine I came across some codepath that deals with the case of BitBlt or MaskBlt -ing across HDCs on different displays. As per the documentation of these functions
BitBlt returns an error if the source and destination device contexts represent different devices. To transfer data between DCs for
different devices, convert the memory bitmap to a DIB by calling
GetDIBits. To display the DIB to the second device, call SetDIBits or
StretchDIBits.
and (MaskBlt)
When used in a multiple monitor system, both hdcSrc and hdcDest must
refer to the same device or the function will fail. To transfer data
between DCs for different devices, convert the memory bitmap
(compatible bitmap, or DDB) to a DIB by calling GetDIBits. To display
the DIB to the second device, call SetDIBits or StretchDIBits.
However this was written in a time before merged framebuffers were commonplace. These days on multi-display systems what you normally have is one large framebuffer of which (different) portions are scanned out to the display output. So logically it behaves as one single display toward GDI.
I wonder if with current versions of Windows (i.e. everything after, including Windows-7) there actually can occur a situation where HDCs acquired from windows, or created with CreateCompatibleDC may actually live on different devices?

Shared bitmap across processes

How to create a device independent bitmap in windows using win32/mfc that will be shared among all processes running on the machine?
Looking for a best and fastest way of sharing a DIB between all processes on windows XP/7 machine. Processes should be able to lock the contents of bitmap and make drawing on this bitmap and other processes can use this bitmap for reading also.
For e.g. initially this DIB will be created by a main application. When some other process want to draw something on this process, can lock the contents of this DIB and draw on this bitmap. If some other process want to read the contents of this bitmap, can lock the bitmap and read the bitmap.
Please suggest a best way both in time complexity and space complexity manner. Space complexity means, a process which wants to draw contents on this bitmap should not need to copy all contents on local memory and draw, it should directly be able to take this bitmap in device context and draw in the bitmap.
There is, unfortunately*, no supported way to share GDI handles (such as to bitmaps) between processes.
There is a supported way however to get multiple bitmaps (in multiple processes) to share the same storage.
In your primary process, create a memory section using the CreateFileMapping API.
You have several ways to get the section handle to your various processes -
The simplest of which (as pointed out by Hans Passant) is to simply name the section when calling CreateFileMapping... and then using OpenFileMapping.
If you have a main process that launches the other processes ensure that the section is created with the bInheritHandle of the SECURITY_ATTRIBUTES set to TRUE and the handle will be automatically duplicated into any sub processes - its usual to pass the handle value on the command line of the new process.
Otherwise use DuplicateHandle function to copy the handle into other processes - but you will still need some other kind of IPC to get the handle to the process.
However it happens - You can then call CreateDIBSection in each process to create GDI bitmaps that are backed by the same memory section. Note the comments on synchronizing access to the bitmap. If you have multiple processes trying to write to the bitmap you might need to serialize access at that level.
As an ironic note: Because Win32 is based on Win16 there are a lot of Win16 legacy APIs that deal with window messages and the clipboard that do in fact expect HBITMAP's to be usable from multiple processes. Also (as an implementation detail) on Windows NT 5.x and 6.x bitmaps are allocated by kernel mode drivers from a single system wide handle table and are thus technically valid in any process - However, GDI also stores the process ID of each GDI object in that table and GDI API calls explicitly check the process ID and fail out if called on a GDI handle belonging to another process.

How to pass generated image/bitmap/GDI objects to other process?

I have a process A that generates HBITMAP GDI objects to be painted on the screen. I have another process B which wants to display the content of images that process A creates.
I plan to do the communications/talking using Point-to-Point message queue or by using other message passing; and use shared memory (along with mutex and or events) to share data.
How do I share image data? I read here that the handles of GDI objects are not guaranteed to be shared amongst processes. Sharing using files is not really an option since the images keep changing (but I still consider it if there is no other way).
Adding more to the ingredients, process A is written using eVC4 (PPC2003 SDK) and process B is written using VS2005 (WM 6 Pro SDK). I have working source code of both applications so I can make some modifications to both but not migrating app A to VS2005 for the time being.
Is COM IImage an option?
I prefer native codes but also consider managed codes.
Use CreateDIBSection with a shared memory object HANDLE as the section handle. The HBITMAP you get back from CreateDIBSection may not be sharable with the other process (I don't know), but if the other process ALSO Creates a DIB Section from the same shared memory object, then the bitmap bits will be shared.

Fastest way to pass a file's contents from Kernel to User mode?

I'll try to be brief, but fully descriptive:
This is Windows-specific. Using the Windows Driver Development Kit (DDK).
I am writing a Kernel Mode Driver (KMD) for the first time, having no prior experience in Kernel Mode. I am playing around currently with the "scanner" mini-filter sample which comes with the DDK, and expanding upon it for practice. The "scanner" mini-filter is a basic outline for a generic "anti-virus" type scanning driver which hooks file creates/closes and operates on the associated file to scan for a "bad word" before approving/denying the requested operation.
The end goal is to scan the file with the user-mode application when it is opened, deciding whether or not the mini-filter should allow the operation to complete, without noticeable slow-down to the process or user which is attempting to open the file. I will also want to scan the entire file again when a save is attempted to decide whether or not to allow the save to complete successfully or deny the save. The mini-filter sample lays out the groundwork for how to hook these calls, but is a bit weak in the actually "scanning" portion.
I am looking at expanding the sample to scan the entire file that has been opened, such as to generate a hash, rather than just the first 1k (the sample's limit). I have modified the sample to read the entirety of the file and send it using the same mechanisms within the original sample. This method uses FltReadFile to read the file within the KMD and FltSendMessage to send the buffer to the user-mode component. The user-mode application is using GetQueuedCompletionStatus to grab the notifications from the KMD and process the buffers.
However, I'm noticing that this process seems to be pretty slow compared to a normal open/read in C++ using the standard library (fstream). This method is taking between approximately 4-8 times longer than simplying opening and reading the file in a simple C++ user app. I have adjusted buffer sizes to see if it makes for a noticeable improvement, and while it can help slightly, the benefits have not appeared to be very significant.
Since I am looking to scan files in 'real-time', this rate of transfer is highly disappointing and prohibitive. Is there a faster way to transfer a file's contents from a Kernel-Mode Driver to a User-Mode Application?
I can suggest several solutions:
Use DeviceIoControl with METHOD_OUT_DIRECT transfer type to pass large amounts of data.
Create memory section and map it to your process (remember about limited address space on 32-bit platforms).
Pass file path to your application and open it there.

Resources