File Read/Write Alert Based on Windows Defender Ransomware Protection

The Windows system has its own antivirus software, and Windows Defender contains many unknown functions. The ransomware protection we use today 1 (also called** Controlled folder access ** , Controlled Folder Access), is a very meaningful small function. This feature is available in all series of Windows 10 and Windows Server 2019, but only in* No other antivirus software installed in the system * to see this option.

Generally speaking, what this function does is to monitor several directories 2 specified by the user and preset by the system. Only programs in the white list are allowed to modify their contents, and other programs are not restricted to read files. When writing files An error will be reported, and Windows Defender will* modify behavior * Make an alarm and pop up a window in the notification center. It can be used as a low-profile version of the Tinder Sword😉

This article does not teach you how to enable this function. This official document [^doc-atpconf] has already been written, and it is boring to write again. There are two main purposes of this article.

  1. More detailed warning information - it will be clear when the window pops up,** Which process accessed which directory ** . The default pop-up window only says “Windows blocked an access”, and does not tell us which process or which directory to operate. If you want to see the details, you have to click on the Defender interface, click several times, and then confirm the UAC pop-up box several times, the experience is extremely bad. Also, in Windows Server** Do not remind! Do not remind! Do not remind! **
  2. More detailed alarm history - you can see it in a list,** Which process has visited which directory before ** . In the interface of Defender, you need to click a UAC bullet box to open each detail, which is very safe, but the experience is still very bad! Moreover, the function of viewing history records is only available in Windows 10, and the Defender interface of Windows Server is connected to** Block History This menu has none! **
  3. Here we can draw a conclusion, I am the stupid B who installed Windows Server 2019 on the daily computer…

The way this article achieves these two goals is to intercept the alarm events about the Windows Defender “Controlled folder access” part in the Windows system events, and then push the event details to the desktop through the PowerShell script, so that the operation of the malicious process We can see it in real time.

The completed effect is shown in the figure below. I operate the Documents directory of the host user in WSL, create a test file in it, access is denied, and a notification message pops up at the same time.


Why do I need such a function? Because I installed a lot of pirated games…

Table of contents

  • [Get alarm history log](#Get alarm history log)
  • [Set warning popup window](#Set warning popup window)
    • [PowerShell notification script](#powershell notification script)
    • [Hide the command line window where the script runs](#Hide the command line window where the script runs)
    • [config event monitoring](#config event monitoring)
  • [See effect] (#See effect)
  • [Epilogue] (#Epilogue)
  • [Postscript (20200603 update)] (#postscript 20200603 update)
    • [Reference Documentation](#Reference Documentation)

Get alarm history log

At the beginning, I didn’t know where the log of this function was. I found an Excel official document 3 of the group policy configuration item, searched for the related configuration item of controlled folder access in it, and located it in the group The position in the strategy is 计算机配置/管理模板/Windows组件/Windows Defender防病毒程序/Windows Defender攻击防护/受控制文件夹的访问. here 配置受控文件夹访问权限 In the help of configuration items, several protection modes and related log locations are recorded. There are no settings related to blocking mode and auditing on the Defender interface.

- 修改或删除受保护文件夹内的文件,如“文档”文件夹
- 写入磁盘扇区


Windows Defender 防病毒会自动确定可以信任哪些应用程序。你可以在“配置允许的应用程序”GP 设置中添加其他受信任的应用程序。
默认的系统文件夹自动受保护,不过你可以在“配置受保护的文件夹”GP 设置中添加文件夹。

- 不受信任的应用尝试修改或删除受保护文件夹中的文件
- 不受信任的应用尝试写入磁盘扇区
Windows 事件日志将在“应用程序和服务日志”> "Microsoft" > "Windows" > "Windows Defender" >“可操作”> "ID 1123" 下记录这些阻止操作。

- 不受信任的应用尝试修改或删除受保护文件夹中的文件
- 不受信任的应用尝试写入磁盘扇区
这些尝试将不会记录在 Windows 事件日志中。

- 不受信任的应用尝试修改或删除受保护文件夹中的文件
- 不受信任的应用尝试写入磁盘扇区
Windows 事件日志将在“应用程序和服务日志”> "Microsoft" > "Windows" > "Windows Defender" >“可操作”> "ID 1124" 下面记录这些尝试。

- 不受信任的应用尝试写入磁盘扇区
Windows 事件日志将在“应用程序和服务日志”> "Microsoft" > "Windows" > "Windows Defender" >“可操作”> "ID 1123" 下面记录这些尝试。

- 不受信任的应用尝试修改或删除受保护文件夹中的文件
这些尝试将不会记录在 Windows 事件日志中。

- 不受信任的应用尝试写入磁盘扇区
- 不受信任的应用尝试修改或删除受保护文件夹中的文件
只有尝试写入受保护的磁盘扇区的操作才会记录到 Windows 事件日志中(在“应用程序和服务日志”> "Microsoft" > "Windows" > "Windows Defender" >“可操作”> "ID 1124" 下)。


From here we can see that the alarm logs related to controlled folder access are located in the system log viewer in “Applications and Services Logs” > “Microsoft” > “Windows” > “Windows Defender” > “Operational” > “ID 1123” and 1124 in. Among them, 1123 is the log of successful blocking when the protection mode is “Block”, and 1124 is the warning log that is recorded but not actually blocked when the protection mode is “Audit only”.

In addition, during actual use, it is found that ID 1127 is also a warning log of this function, which will be triggered when a non-whitelisted program writes to a disk sector.

After knowing the specific location of the log, we can follow the map to view the log of the controlled folder access function in the log viewer.

In order to facilitate our quick retrieval of these logs in the future, we can save the log filter as a custom view. As shown in the figure below, set the event source to Windows Defender, containing the event ID 1123,1124,1127 That’s it.


Now it is very convenient for us to look at the history.

Set alert pop-up window

With the event log in hand, we can use the Task Scheduler to create a task to run a command-line action with the specified event (in this case, a Windows Defender alert) as a trigger. In this way, when Defender finds an unknown program, we can receive the notification as soon as possible.

PowerShell notification script

Let’s first think about how to write this script. In order to ensure the best user experience, I hope this script can achieve the following points:

  1. The Native experience pops up in the form of a toast notification, which can be viewed in the Windows notification center. There is a notifier 4 that can pop up a messagebox on the desktop, which is ugly.
  2. The content of the notification contains the details of each alarm,* what process * visited* what directory * . Rather than the same pop-up every time.
  3. Do not pop up the black box of the command line window. Even if it’s fleeting, it’s not elegant, and it’s scary.

The command line arguments should look like this:

"C:\path\to\notifier.ps1" -User $(User) -ProcessName $(ProcessName) -Path $(Path)

The effect of the pop-up notification is as shown in the screenshot at the beginning of the article.

Refer to 5 for StackOverflow, and implement the following script, which can pop up a toast notification message with the incoming parameter 6.

param (
    [string]$User = $(Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username),

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Information
$objNotifyIcon.BalloonTipIcon = "Warning"
# 标题最多显示32个字
$objNotifyIcon.BalloonTipTitle = "检测到受限文件夹访问"
# 内容最多64个字,120个英文字符

function ConcatPath($Path, $MaxLength) {
    $filename = $Path.Substring($Path.LastIndexOf("\"))
    $remain = $MaxLength - $filename.Length - 5
    if ($Path.Length -le $MaxLength) {
        return $Path
    elseif ($filename -gt $MaxLength) {
        return "$($filename.Substring($filename.Length-3))..."
    elseif ($remain -gt 0) {
        return "$($Path.Substring(0, $remain)) [..] $filename"
    else {
        return "[..]/$filename"

if ($ProcessName.Length + $Path.Length -gt 100) {

    $ProcessName = ConcatPath "$ProcessName" 30
    $Path = ConcatPath "$Path" 40

$objNotifyIcon.BalloonTipText = "进程: $ProcessName,访问路径: $Path"
$objNotifyIcon.Visible = $True

In the actual test, the title of a toast message can contain up to 32 Chinese characters, and the content can contain up to 64 characters or 120 English characters, and when it contains a file path, it will waste a lot of space in some inexplicable places, so extra Added a function to trim the final output file name, the effect is not bad.

Hide the command line window where the script runs

This small script also has a shortcoming, because the binary file type of powershell.exe is a command-line program, so when the operating system starts it, a black frame will inevitably pop up. Even with the parameter PowerShell.exe -WindowStyle Hidden There will also be a black frame flashing by, which is very responsive. This issue is also discussed on PowerShell’s Github7. After looking through it, there are probably two solutions.

One is to use Windows Script Host wscript.exe Run a VBS script 7 as a relay to call PowerShell from VBS. Another solution 8 is to compile a small C# program as a transit call to PowerShell. The idea is to use a non-command line program as a transit, and then use the system API to silently start PowerShell.

Here I choose option one and write a VBS script. Because the second option needs to put an unsigned program in the system32 directory (the author’s setting is to put it together with powershell.exe), it is neither safe nor easy to customize.

This script was also written with reference to the discussion 7 in the above issue, but the version written by the original author cannot pass parameters to the script, so I improved it a bit. The VB language is really rubbish. It is very troublesome to process strings. There is no search for docs. You can only find examples. Programming relies on brain supplementation, and debugging relies on error messages. If the error message does not give the reason, it tells me that xx is wrong. Garbage of garbage.

Set args = CreateObject("System.Collections.ArrayList")
For Each oItem In Wscript.Arguments: args.Add oItem: Next

CreateObject("Wscript.Shell").Run("powershell -windowstyle hidden -File """ & Join(args.ToArray, """ """) & """"),0

After the above file is saved, we can use this script to call the PowerShell script windowlessly.

wscript.exe "C:\path\to\powershell.vbs" "C:\path\to\notifier.ps1" -User $(User) -ProcessName $(ProcessName) -Path $(Path)</Arguments>

If you think about it carefully, this operation is still very powerful. Used in penetration, it can perform some operations that the user does not perceive. It is concealed and powerful. It is a great skill.

Configure event monitoring

Next, we will create an event listener. We trigger a bunch of scripts just written through the task plan, and the whole process is opened.

In the task scheduler, create a new task with the configuration shown in the figure below, and select the filter in the trigger Windows Defender As an event source, the event ID is the same as when the event view was created just now, 1123,1124,1127, I forgot whether to configure the above event level or not. I ticked all of them to be on the safe side.


After the trigger is configured, don’t rush to click OK (the system will report an error if you click OK), add a startup program operation in the “Operation” tab, the command is C:\Windows\system32\wscript.exe, the parameters are similar to those described in the previous section, remember to change it to the actual script path, and the following $(User) Do not modify several parts.

"C:\path\to\powershell.vbs" "C:\path\to\notifier.ps1" -User $(User) -ProcessName $(ProcessName) -Path $(Path)

After the wizard completes, we still need some manual configuration. Right-click to export the task just created and save it as XML. in XML EventTrigger add a tag ValueQueries subtags 910, the edited config file looks like this.

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="">
    <!-- ... -->
      <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Microsoft-Windows-Windows Defender/Operational"&gt;&lt;Select Path="Microsoft-Windows-Windows Defender/Operational"&gt;*[System[Provider[@Name='Microsoft-Windows-Windows Defender'] and (Level=1  or Level=2 or Level=3 or Level=4 or Level=0 or Level=5) and (EventID=1123 or EventID=1124 or EventID=1127)]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
        <Value name="Path">Event/EventData/Data[@Name="Path"]</Value>
        <Value name="ProcessName">Event/EventData/Data[@Name="Process Name"]</Value>
        <Value name="User">Event/EventData/Data[@Name="User"]</Value>
  <!-- ... -->

After editing, delete the task you just created in the task scheduler and import this task. The purpose of this modification is to** Event data ** Extract it and save it as a parameter of the event, so that the command line of the event-triggered operation can be used like $(Path) grammar** quote this parameter **, to pass the Event data to the command line.

look at the effect

The final effect of this set of processes is actually the one shown in the picture at the beginning of the article. Any unauthorized file modification or disk sector read/write will eventually pop up a warning.


The folders monitored by Defender can be customized, through the graphical interface (Windows Security Center), PowerShell commands Add-MpPreference -ControlledFolderAccessAllowedApplications And group policy three ways [^doc-atpconf]. The configuration in Group Policy is located at 计算机配置/管理模板/Windows组件/Windows Defender防病毒程序/Windows Defender攻击防护/受控制文件夹的访问/配置受保护的文件夹. If the reader has modified the protection mode in the group policy in the above configuration (modified 配置受控文件夹访问权限 configuration item), the list of protected folders can only be set in Group Policy. kind of hard.


In addition to ransomware protection, Windows Defender also includes many other features that seem to be very safe, such as the nemesis of binary gangsters - Exploit Protection, system tamper-proof based on TPM and secure boot - Windows Defender System Guard, based on hardware virtualization Optimized kernel isolation, Credential Guard (mitigating mimikatz attacks), and a bunch of protection strategy functions for enterprise users. Such a strong antivirus software, it is free to install Win10! You said, do you still need other anti-virus software?

cover picture:

Postscript (20200603 update)

In fact, this article was written several months ago, and the official account was opened a few years ago. But the reason why it was procrastinated until today is that some key technical problems have been solved, and the workflow of synchronously sending Hexo blog content to the official account has become extremely simple. For hours, I just hope that after I finish writing, I click build, and the CI service will be deployed to the CDN immediately. In addition, the clipboard will prepare a layout for me. Anyway, it’s done now. I can even guarantee that this program is definitely the most comfortable writing experience in the Eastern Hemisphere (I have to blow a wave). In order to confuse this set of tool chains, at least three programming languages were used, which benefited a lot during the learning process, and it is worth opening an article to talk about it. All in all, the Rust language is worthy of Amway, and JS is rubbish

Don’t think that I haven’t used those open-source and closed-source official account editors. How rubbish those typesetting tools are are enough to write an article to complain about. There used to be an MM in our department who was responsible for converting the research report Word documents we wrote into For WeChat graphics and texts, the workload of an article is about half a day to a day. It can be compressed to 10 seconds, and it shouldn’t be too much to blow a wave.

Going back to this article itself, it may not be so well written, and it may not necessarily have so many dry goods. Anyway, after reading the article I wrote a few months later, I can find a lot of problems, so I don’t bother to change it😅 , the posting of the article is more of a test of the typesetting format, and it is also an attempt to open up more communication channels for one’s own articles (certainly not just posting to Moments). There have been too many inputs recently, and it is not a problem to keep them in a notebook for the New Year. It is better to write them out for everyone to enjoy.

reference documents

Note: Since external links cannot be inserted in the WeChat official account, if readers see this article in the official account, they can click to read the original text and view the document link cited in the article in the blog.

  1. Defender introduces the official document: Prevent ransomware and threats from encrypting and changing files | Microsoft Docs [^doc-atpconf]: Controlled folder access function configuration official document: Turn on the Protected Folders feature in Windows 10 | Microsoft Docs  ↩︎

  2. The system’s preset protection directories include personal directories ( %USERPROFILE%) and public users ( %PUBLIC%) under Documents, Pictures, Music, Videos, Desktop directories. These directories cannot be removed from the protection list. ↩︎

  3. Searchable Group Policy Excel documentation: Download Group Policy Settings Reference for Windows and Windows Server from Official Microsoft Download Center  ↩︎

  4. Another way to pop up a notification: How can I send a notification to a Windows 10 computer from the command line - Super User  ↩︎

  5. Refer to other people’s PowerShell push notification script: How to keep powershell notification in action center - Stack Overflow  ↩︎

  6. The way PowerShell parameters are defined is much more elegant than bash and python. PowerShell Parameters - PowerShell -  ↩︎

  7. Github discussion: Powershell -WindowStyle Hidden still shows a window briefly · Issue #3028 · PowerShell/PowerShell , my comment: issuecomment-583834582 , refer to other people’s VBS transfer script: issuecomment-522375489  ↩︎ ↩︎ ↩︎

  8. A small program that pretends to be a GUI program and calls powershell: SeidChr/RunHiddenConsole: Created executable can be renamed to powershellw.exe or pwshw.exe……  ↩︎

  9. Official document of task plan advanced configuration: EventTrigger.ValueQueries property - Win32 apps | Microsoft Docs  ↩︎

  10. How to pass event parameters to the command line of the scheduled task: Scheduled Task - Trigerred by Event - Getting data into the scripts as parameters…- Question  ↩︎