Is it required for COM to be initialized to use SysAllocString, SysFreeString and other BSTR handling functions?
The MSDN says
You need to initialize the COM library on a thread before you call any of the library functions except CoGetMalloc
It appears to me that BSTR allocation functions use IMalloc and therefore COM init is not required?
I cannot find official documentation that says you can call these functions without initializing COM but I can take you on a trip down memory lane for some cute observations.
Because Windows 95 ran on machines with 4 MB of RAM, Explorer tries really hard not to load ole32.dll. So hard in fact that the shell team wrote their own mini version of COM and people writing shell extensions were supposed to only call SH* functions, not Co* functions to avoid loading the real COM/OLE stuff if possible.
This blog post says that mini-COM is 100% gone in Windows XP and later but I'm not sure how far back it is theoretically possible for the shell to be in mini-COM mode.
Things get interesting when you realize that Windows 2000 has a shell interface called IShellFolder2 and one of its methods (GetDetailsEx) returns a VARIANT. And VARIANTs can contain a BSTR! IColumnProvider::GetItemData also returns a VARIANT.
With this information you could infer that Windows 2000 could allocate a BSTR without you having to call CoInitialize, just call SHGetDesktopFolder to get a IShellFolder and ask for a property that is returned as a string.
There are however two unknowns here:
Is it possible for Windows 2000 to use mini-COM?
Will the IShellFolder2 implementation in shell32.dll initialize real COM if it has to return a string?
I know that IShellFolder2 and IColumnProvider are involved when a Explorer window is in details mode (or if it needs a tooltip?) so it seems unlikely that the shell would be willing to load real COM for this.
Even if I could confirm all of this it would not really help you because I assume your main target is not Windows 2000.
Related
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.
I am building a simple database interface with QuickWin commands in Fortran. The command APPENDMENUQQ and INSERTMENUQQ provide to call a callback routine. There is a list of pre-defined routines in the documentation.
Question: Is it possible to call a routine created by yourself?
I use Fortran with Intel compiler v14.
See: https://software.intel.com/en-us/fortran-compiler-18.0-developer-guide-and-reference-appendmenuqq-w-s
Yes, it is possible. Instead of one of the predefined names, specify the name of an external subroutinethat has one input argument of type default LOGICAL, that specifies whether the particular menu item is checked or not. [Edit: it's a subroutine, not a function.]
This is documented in the Intel Fortran Language Reference for APPENDMENUQQ. You can also see Using Intel® Visual Fortran to Create and Build Windows*-Based Applications for detailed information on using QuickWin and modifying menus, though I note the text here doesn't show an example of a user callback.
In APPENDMENUQQ, specify the callback in the 4th parameter. I don't know if the Intel Compiler supplies the same examples as its ancestor MS PowerFortran or whether these got lost on its journey to DEC, Compaq and Intel.
In MS PowerFortran, the examples are in the Projects directory - for example, Projects\Samples\FPS\General\Poker. If you have this, have a look at scoring.f90 - quite a few examples of callbacks there. Alternatively, if you can get hold of old MSDN subscription (around 2005-2006) disks, you might find them there.
The callback takes one logical variable. This tells you whether the menu item is checked. Most of the examples of callbacks look like
subroutine xxx(unused)
logical unused
...
return
call unusedqq(unused)
end subroutine xxx
This is different from what Steve has described - the interface may have changed in the transition from MS to Intel.
I am implementing SMBIOS reading functionality for Windows systems. As API levels vary, there are several methods to support:
trouble-free GetSystemFirmwareTable('RSMB') available on Windows Server 2003 and later;
hardcore NtOpenSection(L"\\Device\\PhysicalMemory") for legacy systems prior to and including Windows XP;
essential WMI data in L"Win32_ComputerSystemProduct" path through cumbersome COM automation calls as a fallback.
Methods 1 and 3 are already implemented, but I am stuck with \Device\PhysicalMemory, as NtOpenSection always yields 0xC0000034 (STATUS_OBJECT_NAME_NOT_FOUND) — definitely not one of the possible result codes in the ZwOpenSection documentation. Of course, I am aware that accessing this section is prohibited starting from Windows Server 2003sp1 and perhaps Windows XP-64 as well, so I am trying this on a regular Windows XP-32 system — and the outcome is no different to that of a Windows 7-64, for example. I am also aware that administrator rights may be required even on legacy systems, but people on the internets having faced this issue reported more relevant error codes for such scenario, like 0xC0000022 (STATUS_ACCESS_DENIED) and 0xC0000005 (STATUS_ACCESS_VIOLATION).
My approach is based on the Libsmbios library by Dell, which I assume to be working.
UNICODE_STRING wsMemoryDevice;
OBJECT_ATTRIBUTES oObjAttrs;
HANDLE hMemory;
NTSTATUS ordStatus;
RtlInitUnicodeString(&wsMemoryDevice, L"\\Device\\PhysicalMemory");
InitializeObjectAttributes(&oObjAttrs, &wsMemoryDevice,
OBJ_CASE_INSENSITIVE, NULL, NULL);
ordStatus = NtOpenSection(&hMemory, SECTION_MAP_READ, &oObjAttrs);
if (!NT_SUCCESS(ordStatus)) goto Finish;
I thought it could be possible to debug this, but native API seems to be transparent to debuggers like OllyDbg: the execution immediately returns once SYSENTER instruction receives control. So I have no idea why Windows cannot find this object. I also tried changing the section name, as there are several variants in examples available online, but that always yields 0xC0000033 (STATUS_OBJECT_NAME_INVALID).
Finally, I found the cause of such a strange behavior, — thanks to you, people, confirming that my code snippet (it was an actual excerpt, not a forged example) really works. The problem was that I did not have Windows DDK installed initially (I do have now, but still cannot integrate it with Visual Studio in a way that Windows SDK integrates automatically), so there was a need to write definitions by hand. Particularly, when I realized that InitializeObjectAttributes is actually a preprocessor macro rather than a Win32 function, I defined RtlInitUnicodeString as a macro, too, since its effect is even simpler. However, I was not careful enough to notice that UNICODE_STRING.Length and .MaximumLength are in fact meant for content size and buffer size instead of length, i. e. number of bytes rather than number of characters. Consequently, my macro was setting the fields to a half of their expected value, thus making Windows see only the first half of the L"\\Device\\PhysicalMemory" string, — with obvious outcome.
This question already has answers here:
What is a Windows Handle?
(7 answers)
Closed 9 years ago.
How can i get HANDLE to the memory region or mapped file ?
What actually HANDLE is ?
Please do not answer like this :
A handle is an abstract reference to some resourc,e provided to you by
another party (usually the OS), that you can hand back to reference
that resource.
I'm interested in technical side
A HANDLE is just some arbitrary nugget to some data.
For example, it's returned by the following APIs: CreateFile() and OpenProcess() - as you can tell, these two are very different, yet return the exact same data-type.
Or for memory, you can get access to the heap (which is returned as a HANDLE from GetProcessHeap()) and then use HeapAlloc() against it.
As MSDN points out, it's used in many other contexts:
http://msdn.microsoft.com/en-us/library/windows/apps/ms724211%28v=vs.85%29.aspx
Access token
Communications device
Console input
Console screen buffer
Event
File
File mapping
I/O completion port
Job
Mailslot
Memory resource notification
Mutex
Named pipe
Pipe
Process
Semaphore
Thread
Transaction
Waitable timer
If you do just want to know what it is:
In simple operating systems such handles are really only pointers to a structure in Kernel space. The structure contain more information about the handle itself (e.g. pointer to a file structure). More complex operating systems like Windows will check the validity of a handle before trying to access this structure.
Because the HANDLE is opaque in Windows (this means: Microsoft says: Do not interpret it - it is just a 32-bit number) the actual meaning of a HANDLE may be different in different versions of Windows. Even within one Version (e.g. Vista 32-bit vs. Vista 64-bit or XP SP2 vs XP SP3) the (internal) meaning may be different.
Microsoft may change the meaning anytime they want to change it (it may be a pointer in Windows 95 but an index into an array in Windows 8 - who knows).
Handles in windows used to be pointer to a pointer to memory location of an object. In win 3.1 days some program cast some kind of handle to see what's behind. Today to my knowledge this is not possible anymore, they are simple unique identifier or token to communicate between you and the system. Some more information http://en.wikibooks.org/wiki/Windows_Programming/Handles_and_Data_Types some more from msdn read paragraph object in 16 bits windows http://msdn.microsoft.com/en-us/library/ms810501.aspx
What is the best way to design a C API for dlls which deals with the problem of passing "objects" which are C runtime dependent (FILE*, pointer returned by malloc, etc...). For example, if two dlls are linked with a different version of the runtime, my understanding is that you cannot pass a FILE* from one dll to the other safely.
Is the only solution to use windows-dependent API (which are guaranteed to work across dlls) ? The C API already exists and is mature, but was designed from a unix POV, mostly (and still has to work on unix, of course).
You asked for a C, not a C++ solution.
The usual method(s) for doing this kind of thing in C are:
Design the modules API to simply not require CRT objects. Get stuff passed accross in raw C types - i.e. get the consumer to load the file and simply pass you the pointer. Or, get the consumer to pass a fully qualified file name, that is opened , read, and closed, internally.
An approach used by other c modules, the MS cabinet SD and parts of the OpenSSL library iirc come to mind, get the consuming application to pass in pointers to functions to the initialization function. So, any API you pass a FILE* to would at some point during initialization have taken a pointer to a struct with function pointers matching the signatures of fread, fopen etc. When dealing with the external FILE*s the dll always uses the passed in functions rather than the CRT functions.
With some simple tricks like this you can make your C DLLs interface entirely independent of the hosts CRT - or in fact require the host to be written in C or C++ at all.
Neither existing answer is correct: Given the following on Windows: you have two DLLs, each is statically linked with two different versions of the C/C++ standard libraries.
In this case, you should not pass pointers to structures created by the C/C++ standard library in one DLL to the other. The reason is that these structures may be different between the two C/C++ standard library implementations.
The other thing you should not do is free a pointer allocated by new or malloc from one DLL that was allocated in the other. The heap manger may be differently implemented as well.
Note, you can use the pointers between the DLLs - they just point to memory. It is the free that is the issue.
Now, you may find that this works, but if it does, then you are just luck. This is likely to cause you problems in the future.
One potential solution to your problem is dynamically linking to the CRT. For example,you could dynamically link to MSVCRT.DLL. That way your DLL's will always use the same CRT.
Note, I suggest that it is not a best practice to pass CRT data structures between DLLs. You might want to see if you can factor things better.
Note, I am not a Linux/Unix expert - but you will have the same issues on those OSes as well.
The problem with the different runtimes isn't solvable because the FILE* struct belongs
to one runtime on a windows system.
But if you write a small wrapper Interface your done and it does not really hurt.
stdcall IFile* IFileFactory(const char* filename, const char* mode);
class IFile {
virtual fwrite(...) = 0;
virtual fread(...) = 0;
virtual delete() = 0;
}
This is save to be passed accross dll boundaries everywhere and does not really hurt.
P.S.: Be careful if you start throwing exceptions across dll boundaries. This will work quiet well if you fulfill some design creterions on windows OS but will fail on some others.
If the C API exists and is mature, bypassing the CRT internally by using pure Win32 API stuff gets you half the way. The other half is making sure the DLL's user uses the corresponding Win32 API functions. This will make your API less portable, in both use and documentation. Also, even if you go this way with memory allocation, where both the CRT functions and the Win32 ones deal with void*, you're still in trouble with the file stuff - Win32 API uses handles, and knows nothing about the FILE structure.
I'm not quite sure what are the limitations of the FILE*, but I assume the problem is the same as with CRT allocations across modules. MSVCRT uses Win32 internally to handle the file operations, and the underlying file handle can be used from every module within the same process. What might not work is closing a file that was opened by another module, which involves freeing the FILE structure on a possibly different CRT.
What I would do, if changing the API is still an option, is export cleanup functions for any possible "object" created within the DLL. These cleanup functions will handle the disposal of the given object in the way that corresponds to the way it was created within that DLL. This will also make the DLL absolutely portable in terms of usage. The only worry you'll have then is making sure the DLL's user does indeed use your cleanup functions rather than the regular CRT ones. This can be done using several tricks, which deserve another question...