Impact of calling CoInitializeEx-CoUninitialize without COM operation - winapi

We have a situation that one of our DLL is using COM operations, rest time COM is not in use.
But since it is inside a DLL, we have to initialize it in main start and uninitialize at main end.
There is a high chance that COM functionality DLL will not load at all, if it is not required. Would there be any impact of calling CoInitializeEx and CoUninitialize?

Related

How to hook any API call on windows x64, x86?

I'm working on a way to hook any API call to perform some verification on the function. (I'm creating a SandBox)
The first way that I think about, is with register key, and implement our own dll into MicrosoftNT to be able to redirect any defined syscall. https://www.apriorit.com/dev-blog/160-apihooks .
Problem? only work on 32 bit, and if the binarie is loading User32.dll, so it's abig issue.
The second way is to inject a dll into a process? Simple but impossible, most program is defended from those injection, so it's not possible.
The last way that I think was to modify the SSDT to change the function address by mine and redirect to the original by creating a driver. Or by InlineHook and just modify the first byte of each address that I want.
The Problem, only working on 32 bit, because windows add a PatchGuard on the Kernel, so we can't do that.
We can delete de PatchGuard but, anticheat will notice the technique.
For the Sandbox I think it won't be a problem to delete a PatchGuard.
The main problem is for real time analysis, I have no more idea how I can do to hook every API call that I want, on any windows OS. I mean on 32 and 62 bit.
I'm a beginner in this domain I started this week so I'm open to any suggestion.
You say you want to hook every API call for a sandbox but then reference the SSDT? Those are two very different things. Do you want to hook VirtualQuery(Ex) or do you want to hook NtQueryVirtualMemory? From kernel or user mode? Or maybe you're referring to all loaded module exports as well as kernel system services?
WinApi
Iterate all loaded modules as well as installing an event to hook all future modules loaded. For each one you will iterate all exports and apply a hook of your preference which all jump to some handler. This handler should be raw assembly that preserves the CPU state, calls some method that does the logging and filtering, restores CPU state, before finally jumping to the original.
Syscalls
Disable Patchguard and apply hooks to every method in the service table similar to the WinApi method described above. This is definitely not suitable for production for obvious reasons.
Use an instrumentation callback which uses ZwSetInformationProcess to redirect most syscalls to an arbitrary assembly block. You can extract the syscall id here as well as parameters. Universal support is an issue though as it wasn't introduced until W7 iirc and you have a lot of limitations prior to W10.
Map a wrapper module that has a hook for every syscall into each newly loaded process from kernel. These hooks will apply to ntdll and simply invoke an NtDeviceIoControlFile call with the syscall id and arguments, forwarding it to your kernel driver for processing. This is commonly employed by antivirus software to monitor user mode system calls without disrupting Patchguard.
The most approved method would probably be callbacks. You can register process and thread callbacks in kernel, stripping handle access at your leisure. This will give you full control over process and thread access from external processes, and you can add a file minfilter to similarly restrict access to the file system.

Prevent out-of-proc server shutdown while it has loaded in-proc server object instances

I have an application which uses an out of process COM server to access a COM object created by an in-proc COM server. This means that the out of process COM server has to load the in process COM DLL to create the final object which it would then return.
For example:
// Create an object which resides in the out of process COM server
container.CoCreateInstance("HelperServerProcess");
// Grab a reference to an object which resides in an in process COM server DLL,
// hosted by the out of process COM server
object = container.GenerateResults();
// Release the object instantiated by the out of process server
container = NULL; // or return, or go out of scope, etc
// This call will fail, because the out of process server has shutdown unloading
// the inproc DLL hosting <object>
object.DoStuff();
However, once the container object is released, the final server process reference (in CoReleaseServerProcess ) is released, and the server shuts down. This results in an E_RPC_SERVER_UNAVAILABLE error when trying to use the result object. At the same time the in-proc DLL hosted in this EXE server still has outstanding objects and therefor returns S_FALSE from CanUnloadNow.
I think adding IExternalConnection to the EXE server 's class factory to manually do reference counting on the remote references will not help, because the objects registered by the DLL in-proc server will use the DLLs class factory and try using IExternalConnection on this factory. Also, if the server spawns interactive child objects in its process space it wouldn't trigger IExternalConnection either way.
It also isn't possible to modify the DLL's reference counting to use CoAddRefServerProcess / CoReleaseServerProcess as the DLL doesn't have access to the container's shutdown code in case it triggers the last release, and third party DLLs can't be changed anyhow.
The only method which I can think of which might work is adding a loop after the server refcount hits zero, which calls CoFreeUnusedLibraries, and then somehow enumerates all loaded COM DLLs and waits until none are loaded and ensures the server refcount is still zero. This would leak processes if a loaded DLL does not implement CanUnloadNow correctly, and involves messing around with low level COM implmentation details which I would like to avoid.
Is there any easier way to ensure that the COM objects instantiated by class factories of in-proc servers keep the process alive, or to enumerate the class factories of DLLs loaded into the current process and query them for the number of references?
Update: Another method which may work, but sounds very much like the sort of things you aren't supposed to do: intercepting every spawned thread in the process, registering a CoInitialize hook via CoRegisterInitializeSpy, and adding server process reference for every thread that currently has COM initialized.
The out-of-proc EXE can delegate the DLL object rather than return it directly. Have GetResults() return an object that the EXE implements, and have that implementation use the DLL internally as needed. This way, the EXE will not be released until the caller releases the EXE's object, thus keeping the EXE's own refcount active. The EXE's object can implement the same interface that the DLL object implements. This way, the caller does not know (or care) that delegation is being used.

How to override an application's single instance limit in Windows?

I am trying to override the singe instance limit of an application for which I don't have the source. I know that the app is using the good ol' trick of using CreateMutex to determine whether there is another instance running. (If the mutex is created successfully it proceeds, if getlasterror says that the mutex has been created it quits immediately). I found that through sniffing the Win32 api calls.
I thought using Detours would do the trick, but it doesn't quite work out. I am intercepting CreateMutexW, but for some reason, it doesn't catch the first four calls to it. (Again I know what these calls are by sniffing win32 calls and looking at the name of the mutexes). I do get the fifth one intercepted, but the one I actually want to intercept is the first one.
I am using detours through the sample application withdll. I wonder if the problem is that detours is kicking in too late or because of some kind of protection these calls may have. Is detours the best approach? Perhaps using something else may be a better idea?
There might be several reasons for the situation you describe. Here are the most probable of them:
The CreateMutexW call you need to catch occurs within the DllMain
method of one of the DLLs that are imported by the process, and you
are using the DetoursCreateProcessWithDll() function to inject your
code. Detours injects your DLL by placing it at the end of the
process executable import list, and hence all the DLLs that are
imported by the process would be loaded and initialized within the
process prior to yours. In order to overcome this, try using
CreateProcess(CREATE_SUSPENDED) and CreateRemoteThread()-based
injection, although this method raises its own challenges.
The API that is used in the first call is different. Have you tried
overriding CreateMutexExW? Are you sure ANSI methods call Unicode
ones?
Hope this helps.

Unable to create a com object using proxy stub dll

Using Visual c++ 6.0, I have created an ATL based .EXE server .
(VC6 as I am dealing with legacy code, a .exe server as I need to test operation in an out of process context, currently the .exe server is essentialy a no op)
I have built and registered the corresponding proxy stub DLL.
I have a client app that does
CoCreateInstance of IUnknown which invokes FinalConstruct in server object and succeeds (so server is correctly invoked)
OleRun of returned IUnknown interface succeeds
QueryInterface on IUnknown pointer for my server object fails with error code of 0x8000402 (No such interface supported) for the IMarshall interface
These steps were copied from (comip.h::CreateInstance)
The problem appears to be that the proxystub dll is not being invoked (it doesn't appear in the Modules list in the IDE, nor in loaded modules list in debug window)
The OleCom Object viewer for my class and interface can be seen here https://skydrive.live.com/redir?resid=AE43106917EBD9E1!191&authkey=!AIOWeS5P3o2mlpw
8891..ca4d is the class interface id for my object
A298...420c is the interface ID for my server object (IDispatch based)
TIA for any assistance
It's possible that your issue is that the component that is implementing the IRunnableObject interface isn't registering itself in the Running Object Table. This will mean that the CoCreateInstance itself will succeed, however, when the object it called on, the RPC code will be unable to find it.
This MSDN page indicates:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms694517(v=vs.85).aspx
Notes to Implementers
The object should register in the running object table if it has a
moniker assigned. The object should not hold any strong locks on itself;
instead, it should remain in the unstable, unlocked state. The object
should be locked when the first external connection is made to the object.
I'm a little worried about why you're also using the IMarshall interface. Normally it's not necessary to write custom marshaling code, thus you won't need to use this interface.
As long as you don't reference a custom interface the default marshaller in ole32.dll or oleauto32.dll will be used. That's most likely why you don't see your proxy being loaded.
In the case of most COM interfaces, the proxies and stubs for standard
marshaling are in-process component objects which are loaded from a
systemwide DLL provided by COM in Ole32.dll.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms692621(v=vs.85).aspx

Is it true that COM services can't be used by multiple programs at the same time?

Before the application terminates its
execution, COM must be shut down
again. (Failure to shut down COM could
result in execution errors when
another program attempts to use COM
services .)
The above quote implies that, right?
No it doesn't.
If you fail to properly release all references to an out of process COM server and correctly close down COM it could lead to that instance of that service being in an odd state (everything should be OK after releasing all references, but sometimes COM might cache part of the out of process marshalling layer).
An out of process COM service can be designed to have separate component instances for each client (within or across services) that are completely independent (even if hosted in the same process), in which case it is hard to see how a failure of one client would affect other instances (other than wasting memory on instances until COM finally times them out). If the instances share state they can of course interfere even if the clients operate perfectly to the rules.
It is rather important that you quote the source of that quote so we can get the context. As near as I can see, you got that from a book about DirectShow programming. What it actually refers to is the need to call CoUninitialize().
Yes, that's kinda important. A thread should call CoInitializeEx() to initialize the COM infrastructure before it starts using any of the COM API functions. You really should call CoUninitialize() when that threads ends so stuff is properly cleaned up. Typically at the end of your program's main() function. Failure to do so may make another app fail when it finds a register class factory that in fact is dead.
This otherwise has nothing to do with a COM out-of-process server having to restrict itself in any way. You specify sharing mode with the REGCLS argument to CoRegisterClassObject(). Of course, a server should not exit and call CoUninitialize until all its objects are released.

Resources