Detect the Application which requests "services.exe" to start a service in Windows - windows

As a part of my project, I get an event notification every time a Service is Started or Stopped using the WMI class Win32_Service through an EventSink.
I want to detect the application which had requested "services.exe" to start a particular service.
Till now, I tried Monitoring ALPC calls between any process and "services.exe" and got a Message_ID every time a process communicates (sends/receives) any information to/from "services.exe" using the ALPC Class. I would like to know what these messages are so that I can decode a StartService() or a StopService() procedure.
Is there any way to detect which application starts/stops a service?

The best way to do this, in my opinion, would be from kernel-mode using the PsSetCreateProcessNotifyRoutine/Ex/Ex2 kernel-mode callback.
If you're going to be using PsSetCreateProcessNotifyRoutine, you will receive less information than if you were using the Extended version of the kernel-mode callback (the Ex one). However, you can still query information such as the image file path of the parent process (or the one being created) by using PsLookupProcessByProcessId to get a pointer to the _EPROCESS structure and then relying on SeLocateProcessImageName (undocumented, however it is accessible in WDK by default).
The SeLocateProcessImageName routine will rely internally on that _EPROCESS structure, since information like the path of the process image on-disk is all tracked by the Windows kernel there.
If you're going to be using the Ex version of the kernel-mode callback, then you eliminate the need to do what is mentioned above. The Ex version of the routine is more recent than the non-Ex version.
The routine prototype for the callback routine will be:
VOID
CreateProcessNotifyRoutineEx(
PEPROCESS Process,
HANDLE ProcessId,
PPS_CREATE_NOTIFY_INFO CreateInfo
)
As seen above, you get a pointer to the _PS_CREATE_NOTIFY_INFO structure. You can then access the ImageFileName and CommandLine fields to filter for services.exe (make sure you filter properly to not catch it for a rogue copy - so ensure full path indicates its the real one) and gain more insight into why it was being invoked (if such information is exposed via the command-line... I cannot remember - nonetheless, you can still detect its creation and be aware of who spawned it).
To determine the parent who was responsible for the process creation operation of services.exe (e.g. if it relied on the Service Manager which in turn resulted in the spawning of it), you can rely on the ParentProcessId field (under the _PS_CREATE_NOTIFY_INFO structure as well). The SeLocateProcessImageName trick will work perfectly here.
SeLocateProcessImageName is undocumented so here is the routine prototype:
NTSTATUS
NTAPI
SeLocateProcessImageName(
PEPROCESS Process,
PUNICODE_STRING *ImageName
);
At-least with the latest Windows 10 WDK, it's already available by default. If you wanted to though, you can use a dynamic import with MmGetSystemRoutineAddress.
Resources:
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex2
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/wdm/nf-wdm-mmgetsystemroutineaddress
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/nf-ntifs-pslookupprocessbyprocessid
https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntddk/ns-ntddk-_ps_create_notify_info

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.

Kauth event upon start process. - prevention capabilities

I'd like to get event in kernel on each new process that starts (fork+execve or posix_spawn), and be able to prevent this operations.
The first option would be using Mac framework named mpo_vnode_check_exec by Hooking to this method with function that return 0 when access is granted or check deferred to next hook.. non zero returned value means access is refused right away.
Unfortunately, this framework is unsupported by apple, and I wish to use a stable alternative like kauth fileop scope with KAUTH_FILEOP_EXEC flag.
However, this framework is for detection only and lacks prevention capabilities..
Perhaps there's a way to prevent the process from running when I get relevant kauth callback on process creation, or halt the process from running until I decide whether it should run or not (and enforce the verdict in another thread).
thanks
However, this framework is for detection only and lacks prevention capabilities..
Correct, if you're only focussing on the File scope.
Register with the Vnode scope and your callback returns whether or not access is allowed.
kauth_listen_scope(KAUTH_SCOPE_VNODE, &myCallback, NULL);
Finally, note that this scope is very noisy, as every type of access to every resource is reported.

Hookin CreateProcessEx

i would like to systemwide hook CreateProcessEx
it is redirects all windows calls into my wrapper function
where I will log names to textfile then call oruginal CreateProcessEx
Can it be easy and safely done ?
I would like hook all systemwide calls to it but not etternaly
for some period of time only.. How to do it?
If I will find the adress of this api call in ram then overvrite
it with call to my procedure, how then I will call the oryginal
function if there it is somewhat corrupted?
Hooking CreateProcess is the wrong approach for a few reasons. There is an approved mechanism for doing this sort of thing but you need a driver to be loaded. Your driver can then simply leverage the PsSetCreateProcessNotifyRoutine function.
With that said, would your needs not be served by using the auditing functionality built into Windows? Turning on process creation auditing will cause the system to write an event log entry whenever a process is created, detailing plenty of information about the process being started, including the image path.
CreateProcessEx() is a user-mode function. You have to patch it on a per-process basis. That means creating a DLL that is injected into every running process, such as by using SetWindowsHookEx() or the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs Registry key, and then have that DLL patch the PE Imports table of every process it is loaded into.

Hooking or Monitoring Service Creation

I am at the end of my rope here. I have been trying for three weeks now to get this information. Before I continue I want you to know I am not writing malware here. I am however writing a binary analysis tool that monitors the behavior of malware.
What I am trying to accomplish is either to hook or monitor CreateServiceW and CreateServiceA. The reason is I want to know what process invoked CreateService and what the binary is that is being registered as a service by the call.
I am tried everything from writing hook ZwRequestWaitReplyPort to intercept the LPC message, to writing a proxy DLL for advapi32.dll, and writing an inline hook for the CreateService function. None of these approaches have yielded results though. The proxy DLL was promising in testing, but didn't work when the official DLL in system32 was replaced with the proxy (BSOD). The inline hook would work if I could gain write access to the mapped area of memory the DLL lies in. But regardless my time is running out and I am desperately in need of an alternative.
I have looked at SetWindowsHookEx and it seems plausible that it might be able to intercept messages sent from the process to services.exe ...but I am not certain.
Can anyone point me in a good direction...I'm begging you.
"The inline hook would work if I could gain write access to the mapped area of memory the DLL lies in."
If it's a system that you fully control, why don't you have write access to the memory?
Use VirtualProtect to change the permissions to RWX and put your hook in. The ADVAPI32 CreateService routines are just stubs forwarded to sechost.dll via api-ms-service-management-l1-1-1.dll (due to MinWin) so there is already easy call instruction to hook.

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