Kauth event upon start process. - prevention capabilities - macos

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.

Related

Is it possible to call functions from a kernel mode driver in a user mode application on Windows?

I read here that the inverse is possible, but how does one achieve such a thing? I'd hope there's a simple way, similar to calling from a loaded DLL, but my google research comes up with nothing. My only other thought is that one could pass some predefined constants through WriteFile or DeviceIoControl that the driver parses like a switch statement to execute the relevant function; does a more direct method exist?
The question is why would you want to do it? Generally if you have to rely on some mechanism like this, you need to revisit the design of the application/driver that you are writing.
The correct way to do something in context of your user mode application is exactly what you described. You can do a DeviceIoControl call to your driver and the driver validates all the parameters that you have passed, then carries out the operation on behalf of the user mode call.
If for some reason, you need to call into kernel directly, you will have to resort to undocumented methods. There are ways to hook into kernel dispatch table and overwrite one of the dispatch handler to redirect the call to your function. But I hope you never ever ship anything like this to your customer. This is good for learning how the dispatch table works, etc but introduces several security nightmares. Ultimately your software should not be responsible for someone's machine getting hacked.

Windows Antimalware Scan Interface thread safety

The Windows Antimalware scan Interface (AMSI) contains abstractions which can be used to call the currently active virus scanner in Windows:
https://learn.microsoft.com/en-us/windows/desktop/amsi/antimalware-scan-interface-functions
There are 2 methods related to initialization:
AmsiInitialize
AmsiUninitialize
AmsiInitialize returns "A handle of type HAMSICONTEXT that must be passed to all subsequent calls to the AMSI API.".
After initialization is complete, I can use AmsiScanBuffer to scan a buffer for malware.
My question:
Can I use the same context concurrently from many threads in my application, or do I need to create one per thread from which I'm going to call the methods?
Reading the documentation, for AsmiUnitialize, it tells me that When the app is finished with the AMSI API it must call AmsiUninitialize.. This tells me that the context can be used for many calls, but it doesn't tell me anything about thread safety or concurrency.
Generally, API calls that are not specifically marked as thread-safe are not (this is usually true for any library). The easiest solution is to open an AMSI handle per thread.
(P.S. This only works with Windows Defender so far as I 've tested).

Detect the Application which requests "services.exe" to start a service in 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

how to prevent multiple program loading in windows?

I am developing an windows application.
what I want is to prevent this application running multiple in single OS.
(e.g. we can run multiple instance of notepad.exe, calc.exe at the same time... but I don't want this)
what is the most effective way to implement this?(preventing multiple instance of process running at same time)
I'd rather not use methods like checking process names or sharing some global file as a signal... since it is too easy to circumvent
thank you in advance
This is typically done with mutexs. When your process launches you call CreateMutex and check the return value. If it succeeded then this is the first launch, otherwise there is another instance of your process alive. Your mutex should be in the Global\ namespace. Also make sure to ReleaseMutex when your program finishes running.
What framework are you using? I'm assuming it's .Net? Here's a post from an msdn foum on the same thing.
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3e139912-45ea-432e-b9e0-e03640c07c9f/
You mentioned you don't want to check current process names or use a global file.
Lock the current executable
.NET example code:
System.IO.File.Open(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.None);
The FileShare.None keeps any other process (like Windows Explorer) from executing the file until the app closes or the file handle (returned object) is explicitly closed.
Global Mutex
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411%28v=vs.85%29.aspx
If the mutex is a named mutex and the object existed before this
function call, the return value is a handle to the existing object,
GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored,
and the calling thread is not granted ownership. However, if the
caller has limited access rights, the function will fail with
ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.
Global mutex is the easiest way. To clarify another answer you don't just check the return value you check the GetLastError value as well.

access violation in wglMakeCurrent

Sometimes in my OpenGL application I get an access violation in the following API call:
wglMakeCurrent(NULL, NULL);
The application only has one single thread, and I've checked that before that call, both the DC and HGLRC that are currently used are correct and valid.
There are three different windows with OpenGL content, and they're all redrawn on WM_PAINT messages and if a refresh is required due to user interaction (e.g., picking an object).
Also this access violation happens on different machines with different graphic cards, so I don't think it's a driver issue.
What could make this API call crash? What should I investigate in the app code to find out where/why this happens? I'm really lost here since I've checked everything I could think of already. I hope someone can give me hints/ideas on what more to check.
Is the purpose of this call to release the current thread's device context? That is the only time passing NULL for both parameters is valid. From the documentation:
"If hglrc is NULL, the function makes the calling thread's current rendering context no longer current, and releases the device context that is used by the rendering context. In this case, hdc is ignored."
Further to Tarydon's suggestion of adding a glFlush, it appears this would be redundant:
"Before switching to the new rendering context, OpenGL flushes any previous rendering context that was current to the calling thread."
Given the API actually crashes, and does not simply result in a failure, the only suggestion I can think of is that the thread on which you are calling wglMakeCurrent to release the HGLRC is not the same thread context used to associate the HGLRC with that device context. So the driver may be looking up the wrong thread-local storage for the call, thus causing the crash.
What happens if you add some logging to your code and print the current thread ID just before each call to wglMakeCurrent?
See:
wglMakeCurrent reference on MSDN
Turns out that an updated graphics driver fixed the issue. So it was a problem in the driver.
Try adding a glFlush call just before you do this. Perhaps the rendering pipeline has not yet been fully flushed to the GPU.

Resources