Skip to content

Filtering Processes Before Injection #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: capemon
Choose a base branch
from

Conversation

para0x0dise
Copy link
Contributor

@para0x0dise para0x0dise commented Jun 26, 2025

Issue Description

As mentioned in the issue #2608, when I tried to upload PDFs and MS Office documents, it accidentally creates or executes processes such as explorer.exe or svchost.exe, which will trigger false-positive signatures.

After tracking that issue, I found out that Winword.exe or AcroRd32.exe tried to open the explorer.exe process many times, which will eventually create an injection info for that process and send a message to the analyzer to inject the DLLs inside

image

As shown above, the process is opened with the desired access of PROCESS_DUP_HANDLE, so I have decided to make a filtering condition to avoid injecting the DLLs into these processes BASED ON PROCESS'S DESIRED ACCESS.

Drawbacks

This approach is working with any 64-bit working processes, but fails with 32-bit processes with an error code of 193 (%1 is not a valid Win32 application.)

image

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @para0x0dise, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request aims to significantly reduce false positives in the analysis environment by implementing a sophisticated filtering mechanism for DLL injection. It prevents injection into system processes that are opened with non-malicious access rights, thereby improving the accuracy of analysis results, particularly for document-based malware.

Highlights

  • Injection Filtering Logic: Introduced a new filtering mechanism to prevent DLL injection into benign system processes (e.g., explorer.exe, svchost.exe) that are opened with only legitimate access rights. This addresses false positives during analysis of documents that might spawn such processes.
  • Process Access Rights Tracking: Modified the InjectionInfo structure and OpenProcessHandler to store and utilize the DesiredAccess flags used when a process handle is opened. This allows the new filtering logic to make informed decisions about whether to proceed with injection.
  • New Configuration Option: Added a new configuration option, filter_system_injection, which controls whether this new filtering logic is active. This option is enabled by default to immediately reduce false positives.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request effectively introduces a new filtering mechanism to prevent false-positive DLL injections into system processes. The changes correctly propagate the DesiredAccess flags through the OpenProcessHandler and InjectionInfo structure, allowing the ProcessMessage function to make informed decisions based on the access rights used to open a process. The definitions of MALICIOUS_FLAGS and LEGITIMATE_FLAGS are appropriate for distinguishing between benign and potentially malicious process access patterns. The implementation is clean, well-commented, and integrates seamlessly with the existing configuration system, enabling the feature by default to enhance the accuracy of threat detection.

@kevoreilly
Copy link
Owner

Hi para0x0dise, firstly I apologise for not responding to the issue over on the main repo. I had read it and meant to reply, then it just slipped my mind and I completely forgot about it, so sorry about that.

It does look like you have gone down the path I was going to suggest anyway which is great. But I suspect there is a misconception as you mention the use of NtOpenProcess triggering monitor injection, but in fact it doesn't. Looking in Injection.c there is a dedicated function ProcessMessage which triggers monitor injection, and this is invoked by the following functions:

SendNotifyMessageA, SendNotifyMessageW, SetWindowLongA, SetWindowLongPtrA, SetWindowLongW, SetWindowLongPtrW, CreateProcessInternalW, SetWindowsHookExA, SetWindowsHookExW, NtCreateProcess, NtCreateProcessEx, NtCreateUserProcess, RtlCreateUserProcess, CreateProcessWithLogonW, CreateProcessWithTokenW, NtMapViewOfSection, NtWriteVirtualMemory, WriteProcessMemory, NtWow64WriteVirtualMemory64, NtQueueApcThread, NtQueueApcThreadEx, NtCreateThread, NtCreateThreadEx, NtSetContextThread, NtSuspendThread, CreateRemoteThread, RtlCreateUserThread

So for your examples it is definitely worth identifying which of the above apis is responsible for triggering the injection into explorer.

To achieve your goal should be simple. The main drawback in doing this however would be that if ever there were injection from a maldoc into explorer, it would be missed. I'm not sure how improbable or not this might be, but in general it's wise to follow the behaviours only where we can, and avoid blacklists.

I am open to the idea of adding something like this to the blacklist, but firstly I can't actually recreate this myself. When I open a PDF I just get AcroRd32.exe:

image

So definitely worth looking at the Acroreader install and configuration as this issue would be far better avoided at this level than by blacklisting injection in the monitor.

For Excel, again no explorer injection:

image

I do see injection into explorer from my Word processes. When I dug into which api it was caused by, the culprit was SendNotifyMessageW:

image

The code in the hook responsible for triggering the monitor injection is in hook_window.c:

	if (hWnd) {
		our_GetWindowThreadProcessId(hWnd, &pid);
		if (pid != GetCurrentProcessId()) {
			DumpSectionViewsForPid(pid);
			ProcessMessage(pid, 0);
		}
	}

If we find that these are the same trigger as you are seeing, and they are seen in all installations/configurations, it would worth considering adding code in the hook itself to filter these unwanted injections as the more specific the filter the better. For example:

diff --git a/hook_window.c b/hook_window.c
index 8bf7b29..b58df82 100644
--- a/hook_window.c
+++ b/hook_window.c
@@ -272,7 +272,7 @@ HOOKDEF(BOOL, WINAPI, SendNotifyMessageA,
        get_lasterrors(&lasterror);
        if (hWnd) {
                our_GetWindowThreadProcessId(hWnd, &pid);
-               if (pid != GetCurrentProcessId()) {
+               if (!g_config.office && pid != GetCurrentProcessId()) {
                        DumpSectionViewsForPid(pid);
                        ProcessMessage(pid, 0);
                }
@@ -299,7 +299,7 @@ HOOKDEF(BOOL, WINAPI, SendNotifyMessageW,
        get_lasterrors(&lasterror);
        if (hWnd) {
                our_GetWindowThreadProcessId(hWnd, &pid);
-               if (pid != GetCurrentProcessId()) {
+               if (!g_config.office && pid != GetCurrentProcessId()) {
                        DumpSectionViewsForPid(pid);
                        ProcessMessage(pid, 0);
                }

This is enough to prevent explorer injections from my Word process. If you would like to test this here is the monitor (assuming your Office is 32-bit!)

capemon.zip

@para0x0dise
Copy link
Contributor Author

para0x0dise commented Jul 9, 2025

Hi @kevoreilly,

First off, apologies for the delay—I’ve been quite busy lately. Thank you very much for the clarification on DLL injection, by the way! I also discovered the reason behind the crash when injecting into a 32-bit process—it was due to a null pointer dereference 😅.

Now, back to the main issue: I found a way to suppress the noise caused by explorer.exe. As shown in the screenshots, apps like Word (or other Microsoft applications) often call NtOpenProcess on explorer.exe, which then uses PostThreadMessageA to send messages (I'm not sure why). This eventually triggers ProcessMessage, leading to DLL injection into explorer.exe.

image
image

To handle this, one quick solution is to exclude explorer.exe by name within the hook. However, as you pointed out, that could lead to false negatives, especially if a benign-looking app is attempting malicious injection into Explorer. While I haven't seen such a case in practice, I’ve implemented a more reliable method.

I used a variable named g_config.filter_system_safe_process_pid that stores the last PID opened via NtOpenProcess using specific access masks (typically used by legitimate applications). I then compare this PID with the one used in PostThreadMessageA. I’ve tested this approach against several samples, and it seems to work well.

Feel free to take a look and let me know your thoughts!

@kevoreilly
Copy link
Owner

Hi para0x0dise, thanks for your reply. Over the years I have learned that when it comes to monitor dev, little details really matter. Here the statement 'apps like Word often call NtOpenProcess on explorer.exe, which then uses PostThreadMessageA'... omits the really relevant detail. It is an api called by Word that triggers the injection in to explorer, so unfortunately explorer calling PostThreadMessage on Word isn't relevant. It in fact highlights that the interesting bit has already happened, as api logging of explorer requires it to first be injected, which is what we're trying to stop!

So going back to what I said in my previous message, there is an api called by Word which acts on a handle to explorer, and which is not NtOpenProcess. It is crucial to make sure we identify this api before even considering a solution. In order to identify the api in my case, which may well be the culprit in yours, I had to laboriously comment each call to ProcessMessage in order to correlate with the injection into explorer captured in the analysis log. You did not mention whether the dll I shared was any help in this regard.

@para0x0dise
Copy link
Contributor Author

para0x0dise commented Jul 10, 2025

Hi @kevoreilly,

Apologies for not mentioning this earlier — I did test your DLLs (my environment is 64-bit), and I incorporated your condition before rebuilding in 64-bit. Unfortunately, the entire task failed because the DLL caused the application to crash.

if (!g_config.office && pid != GetCurrentProcessId()) {
    DumpSectionViewsForPid(pid);
    ProcessMessage(pid, 0);
}

NtOpenProcess on explorer.exe, which then uses PostThreadMessageA'... omits the really relevant detail. It is an api called by Word that triggers the injection in to explorer, so unfortunately explorer calling PostThreadMessage on Word isn't relevant.

In my particular case, it's Explorer calling PostThreadMessageA that triggers CAPE to inject DLLs and begin monitoring — I'm not sure why this occurs in my setup, but that’s the behavior I’m seeing.

@kevoreilly
Copy link
Owner

That doesn't make sense. Explorer calls something that causes injection into explorer?

@para0x0dise
Copy link
Contributor Author

para0x0dise commented Jul 15, 2025

That doesn't make sense. Explorer calls something that causes injection into explorer?

I'm sure that explorer triggered PostThreadMessageA, but I have no idea why? :)

@kevoreilly
Copy link
Owner

What is needed is to understand that before any apis from explorer can even be captured, the process must first be monitored, therefore injected. Since the initial process is word or excel, and the discussion is about unwanted injection into explorer, the root cause of this problem is an api called by word or excel that causes a hook in the monitor to call ProcessMessage which sends a message to the analyzer to initiate monitor injection into explorer.

It must be one of the apis I listed for which the hook calls ProcessMessage called by the initial process that we need to establish then deal with.

It is difficult to find this api, therefore in order to do it in the case of my 32-bit Office, I added a debug line to every instance of ProcessMessage in api hooks in capemon. If you need me to provide a 64-bit monitor with these added I will recreate it for you. It is also possible to compile the test code I posted in 64-bit form. I am happy to provide this for you to test also. But the first step has to be to establish which api in the initial process triggers injection into explorer.

@kevoreilly
Copy link
Owner

Here is the tell-tale output from the analysis log showing the extra logging I added to the hooks that call ProcessMessage just prior to the first appearance of explorer in the log where it is injected:

...
2025-06-26 14:47:30,392 [root] DEBUG: 4028: SendNotifyMessageW: ProcessMessage 1308
2025-06-26 14:47:30,408 [root] DEBUG: 4028: ProcessMessage: Monitoring process 1308
2025-06-26 14:47:30,408 [root] INFO: Announced 64-bit process name: explorer.exe pid: 1308
2025-06-26 14:47:30,408 [lib.api.process] INFO: Monitor config for <Process 1308 explorer.exe>: C:\5b78en0k\dll\1308.ini
2025-06-26 14:47:30,424 [lib.api.process] INFO: 64-bit DLL to inject is C:\5b78en0k\dll\PSbaeGaw.dll, loader C:\5b78en0k\bin\hAUrLOKK.exe
...

@para0x0dise
Copy link
Contributor Author

Could you please upload the file you are testing?

@kevoreilly
Copy link
Owner

I've compiled a 64-bit monitor for you with each ProcessMessage() logged to the analysis log which should allow correlation with first appearance of explorer.exe in that log. This is simply the result of adding lines such as the following to all ProcessMessage() calls:

@@ -301,6 +305,7 @@ HOOKDEF(BOOL, WINAPI, SendNotifyMessageW,
                our_GetWindowThreadProcessId(hWnd, &pid);
                if (pid != GetCurrentProcessId()) {
                        DumpSectionViewsForPid(pid);
+                       DebugOutput("SendNotifyMessageW: ProcessMessage %d", pid);
                        ProcessMessage(pid, 0);
                }
        }

Let me know the result and we'll take it from there.
capemon_x64.zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants