Windows Events - Part 3 - Disrupt Code Execution with ETW
Windows Events - Part 3 - Disrupt Code Execution with ETW

Windows Events - Part 3 - Disrupt Code Execution with ETW

created time
Dec 3, 2022 05:15 AM
last update
Jan 7, 2023 07:52 AM
Tags

Background

  • This part illustrates how to use Event Tracing for Windows to disrupt malicious Code-Execution.

Outline & Objectives

  1. Controls based on keeping track of “bad” as signatures to block are ineffective because evasion is cheap.
  1. Review some COTS products & gain ideas to disrupt offensive TTPs.
  1. Quick introduction to ETW to prepare you for C# code compilation & step-through of a simple App-Control program.
  1. Simulate Multi-stage or Chained Code-Execution & watch it being disrupted by this simple App-Control, to experience & strengthen understanding of earlier sections.

From Observing to Disrupting

Although it may seems sensible to pay some company to chase after “bad” & supply you with a set of signatures to block attacks, but it is ineffective as we are dealing with an infinite set that can be generated at cheap & fast rate.
notion image
🧠
This entry shares an inverse approach to the problem, focusing on what should run & have clear awareness of how this set of allowed programs can be abused. Why?

Detection Engineering is EXPENSIVE

But evasion is dirt cheap. As someone who delivered millions of dollars worth of Cyber Security Operations Center, trained & led a Testing & Evaluation team to survey a range of Cyber Security start-ups, worked within joint research lab; beyond the technical aspects, I also had privy to many Bill-of-Material. I do have some grasp of costing.
🔥
💰 Signature-based controls are easily evaded by free or very cheap methods… & you WILL BE paying again & again!
Let’s just have some idea how early attack phases are being dealt with today:
Tactics
Paid Signature-Based Controls
Free or Low-Cost Evasions (Tip of Iceberg) Examples
Payload Delivery
Email scanning Network in-line Sandbox Host Anti-Virus, XDR… Web App Firewall
Encrypt with a password protected zip archive, together with deceptive email message to convince victims to unzip & review contents. Email scanning & Sandbox analysis can’t decrypt, thus unchecked. Pack into archive formats like ISO, VHD & various formats that are not subjected to Mark-of-the-Web (aka MoTW bypass). Victims download, mount malicious archives & payload executes. Every now & then, some “researcher” releases the details of bypass methods like → https://www.darkreading.com/application-security/popular-wafs-json-bypass. → more occurrences of such evasions.
Code-Execution
Host Anti-Virus, XDR…
Free Evasive Malicious Office Macro (Optiv is a security company btw) Free Evasive DLL generator Free Powershell obfuscation Free knowledge on refactoring Metepreter (payload from popular free Metasploit framework)… too many to list here
Remote C2
Network in-line Sandbox Firewalls Web Proxies DNS Deny-lists
Self-signed TLS Free automated open Certificate Authority https://letsencrypt.org Free 3rd level domains
A short back story before getting into Attack Disruption Engineering. During my stint as a technical lead for a Test & Evaluation group, I had to train a mid-career staff who was once doing software development but wanted to get into Cyber Security. I provided some technical specifications for the custom malware, basically a screenshot & keystroke logging software that periodically sends captured data to an anonymous email provider. He wrote it in a less than 2 days. In short, attacking Windows is cheap.
After a short brain-storming session, we came up with this idea of a simple Excel macro, that basically does NOTHING when it is NOT within a Windows Domain environment. We also had (then) “cutting edge” in-line network-sandbox & a full fledge SOC to experiment with our new malware, which was delivered to our own laptops, under the nose of SOC & we got hold of screenshots & key-strokes data from the anonymous email service. We weren’t even “State Actors”!
notion image
🔥
It’s not that hard to write your own backdoor! Our cheapo malware is just one of the infinite specimens that we cannot keep out with signature-based approach. Chasing after downstream indicators is a futile & expensive affair! We need something else…

Engineering Attack Disruption

notion image
I picked a couple of non-signature based controls to explain how these Commercial-Off-The-Shelf products disrupt several offensive tactics without chasing after “bad”. THIS IS NOT endorsements of products, but to illustrate tactical disruptions while maintaining usability.

Case Study 1: Disrupting Web-based Malware Delivery & C2 channel

Almost all modern malware needs to report back to Threat Actors somehow. The easiest & widely allowed way would be to the use of HTTPS. As far as network controls is concern, it will look like any web traffic & proverbially hard to find needles in haystacks, which makes it attractive to deliver payloads without being inspected in-transit.
Remote Browsers disrupt Payload Delivery & Code-Execution via browsers (e.g. malicious links within emails) & Remote C2 via the web (including DNS tunnels if done correctly). There’s little to zero logic to detect “bad” for such controls. All web pages users visit are loaded remotely, such that it mirrored only visual representations back to users’ browsers. As far as user experience is concern, it is just like any regular web session. Any malicious codes, exploits or whatever will just detonate within the Remote Browser containers & not at users’ browsers.
notion image
Perhaps there may be some usability issues with certain web-sites & REST-API driven apps that may connect directly, it is a good trade-off because a broad array of exploits (known & unknown) & link-based delivery of malware will be disrupted. Even when malware were to run a removable storage like a USB stick, the outbound call home to C2 servers will fail, thus disrupting Remote C2 over the targeted endpoint.
🧠
Maintain user experience but disrupt malware delivery & C2 communications WITHOUT chasing after BAD lists. It makes the cost of Phase 2 (e.g. deliver phishing emails) to get into networks HIGHER. Just a short digress. Once as lead product evaluator. I taught my team to find out how cheap & easy was it to evade a given control, once the working principles are understood. Very often, organisations that have the budget may just run Cyber Range to simulate attacks for the sake of confirmation bias or just navigating internal office politics. The reality however is a way larger scope than the limited attack simulations that most are performing. Part of your Cyber Intelligence effort should consider prevailing evasions on genres of technical controls (e.g. EDR evasions are in thing), & design defences in a way to reduce your problem space rather than spreading yourself too thin.
Next, I will cover a control that assumes breached.

Case Study Two: Zero Trust File-Level Protection

Source: SecureCircle
Source: SecureCircle
SecureCircle was acquired by CrowdStrike. It focuses on a smaller set of processes that are allowed read (decrypt on behalf) from otherwise encrypted files. Non-allowed app processes will just read gibberish encrypted contents.
Source: SecureCircle
Source: SecureCircle
By defining policies, only allowed users on allowed devices with allowed processes can share protected files (e.g. Source Codes, files related to Intellectual Properties…) that are always encrypted & only decrypted within allowed environments & receivers.
notion image
🧠
Again, agnostic to offensive techniques. Even in an event that attackers were already controlling a terminal remotely, files are gibberish as long as the encryption keys are secured.
Now that you have some ideas of attack disruption, the next few sections will walk you through the thinking process & into practical code step-through of disrupting Download → Write File → Execute kill-chain.

Why Download→WriteFile→Execute?

  1. Microsoft Windows (both server & user zones) is still a very popular target! (System Susceptibility ⇒ Value + Vulnerabilities)
    1. Think of valuable purpose-built networks like hospitals, Point-of-Sale & …
    2. Enterprise services like email, web application & what not services that are exposed to Internet
    3. No end to Microsoft systems’ vulnerabilities & to be fair, even security vendors!
  1. Majority of malware are still Windows based PE files in the formats of EXE & DLL (goodware also uses these formats) (Threat Accessibility; able to deliver such payloads cheaply & widely, regardless direct exposure of vulnerabilities or not)
    1. 95% of millions of samples over the years are EXE & DLLs: https://blog.virustotal.com/2021/10/ransomware-in-global-context.html
    2. A majority of early infiltrations involved written PE files (e.g. backdoors, RATs & so on) see https://thedfirreport.com & assortments of technical analysis available online
  1. Cheap & easy, with countless payload generators, evasion toolkits & tutorials freely available (Threat Capability; tools, techniques & resources in abundance for Threat Actors)
🧠
Although there are so called “Fileless” offensive techniques, a majority of offensive campaigns still rely on file-based approach as their go-to modus operandi until they encounter a harder target, conforming to Least Effort Principle. Since we can’t really change the realities of point 1 & 3, it makes sense to disrupt majority of the problems by denying Portable Executable without the maintanence of Allow or Deny lists! Fight cheap with cheap! Repurpose your budgets to other worthy controls! Is the security product still trying to figure out bad before it can react? Or categorically denying several offensive tactics such that a broad array of techniques/payloads under each offensive tactic becomes irrelevant & evasion non-trivial?

Isn’t there App Control within Windows?

Yes. Microsoft started from Software Restriction Policy to AppLocker to now Windows Defender Application Control. The likely inhibitions to wide adoption (I may be wrong, it’s hard to find accurate stats) are:
  1. Complex for some organisations to enforce & maintain
  1. Some features of AppLocker & WDAC are only available for Windows Enterprise versions
  1. May not be perceived as worth the effort when abusing system tools aka Living Off the Land is becoming common
💰
There are also 3rd party Application Control products too. It boils down to budget & technical resources to manage such technical controls. So when coupled with Deny or Blacklisting approach (to intercept file writes & check against …) like host anti-virus signatures, it’s 2x the cost & support management.
Which is why several vendors are converging such controls into a single “solution” with options (typically subscription-based) to take up. Keep these in mind. For wider adoption of App Control, we need to make it easy, effective & cheap/free to deploy.

Tracking is TEDIOUS, regardless “Good” or “Bad” files

It turns out, even tracking “good”ware is equally tedious. In terms of operations, it is not very different from tracking bad when you need to figure out if it is good or not, distribute the signatures & so on. The most tricky part is “good”ware can be abused to do “bad” things. There are no shortages of examples of signed drivers, system tools & applications that are used for offensive objectives.

Disrupting Download → WriteFile → Execute

notion image
For this ETW intro exercise, we will start with file writes. Just a quick back story to how this came about. Like everyone else who had worked in a SOC with SIEM environment, I started tracking hashes of each executed file (Sysmon.ProcessCreate.Hashes field). In a staged development environment, things were pretty predictable until I started collecting events from 2 of my interns’ personal laptops, who were both using Windows 10 Home edition. There would be a fire-hose of alerts if my initial detection logic were to be deployed in production. To figure out why, I wrote a simple Powershell script to enumerate ALL EXE & DLLs within their Windows & wrote various file attributes into a CSV file.
💡
It was a serendipitous moment when I noticed a field related to file ownership. I expect files created by user, like within Desktop or Document folders owned by user, but what I found interesting was within Windows & its sub-folders…
notion image

Why File Ownership matters?

Notice Owner field & there’s a TrustedInstaller under the Principal column within the earlier screen shot. After examining the CSV files from their laptops, I noticed:
  1. System files & directories that are installed or updated by OS are typically owned by either TrustedInstaller or SYSTEM
  1. Apps that we installed with RunAs admin are owned by Administrators group
  1. Files created within explorer or any processes started by user (e.g. browser, MSOffice…) are owned by user
Which begs the question, how many Portable Executables are owned by users? Since the two Intern laptops were sending Sysmon events into a database, I went to query distinct processes executed & linked them with the file ownership data-set. Btw, I can’t file ownership from any audit & Sysmon events I have used so far…
🔍
It turns out, Microsoft OneDrive was the common process found on the two laptops that were owned by the respective student account. Only one student ran freeware like putty.exe twice. That file was owned by a user account too.
Note that OneDrive application directories are user-writable & turned on by default in Win10 & beyond.
Let’s say you are IT manager, would you want users to delete or change software on their systems? If users can modify files, wouldn’t it be the same for attackers too?
A little Googling will find us stuff like this:
Video preview
Adversaries can easily pull off techniques like the above & since it auto-started when Windows startup, it is a reliable means of backdoor within a compromised Windows. OneDrive is also used as a Command-&-Control (C2) channel as eluded by Trellix researchers.
🧹
For environments with good practice of using Standard-Users for the majority, most malware backdoor files will be owned by users until attackers figured out ways to escalate privilege. As part of a “hygiene” assessment, it is useful to enumerate distinct program files that have poor ownership, especially the ones that are network-bound!

Using File Ownership to disrupt Code-Execution

🔰
With a simple policy: deny files NOT owned by SYSTEM, TrustedInstaller or Administrators group from running.
Notice it is a negative logic because you can’t & won’t want to hard code user account names that may differ across different endpoints. Basically, don’t trust any PEs (including DLLs) that are not owned by SYSTEM, TrustedInstaller or Administrators. Before we start the ETW exercise, let’s explore the following questions:
  1. When to check file ownership?
  1. How to “deny” execution without maintaining a list?
  1. What if malware was already installed before App Control starts?
  1. Will it affect legit software operations & deployments?

When to check file ownership?

We want to disrupt early, so let’s re-look at my Sysmon to TTP mapping table that was used in part 2:
notion image
ℹ️
FileCreate gives us a TargetFilename, which is the full path to the written file, but it does not provide the file owner name, so we need to get owner string programmatically. For this exercise, to keep it simple, we will be using ETW without Sysmon.
notion image
For malicious PE files that could be written before the deployment of a host sensor or control, we have to then rely on ProcessCreate & ImageLoad to check file ownership for EXEs & DLLs (there are other extensions like .CPL & the likes) respectively.

How to “deny” execution without maintaining a list?

Remember the 2 product case studies I shared earlier? They don’t detect “bad” to react. Similarly, for this ETW exercise, we will add a special permission ACL rule to every file NOT owned by NT SERVICE\TrustedInstaller, NT AUTHORITY\SYSTEM or BUILTIN\Administrators. This rule only affects executable files, other file types are unaffected!
Let’s begin with an end in mind, a simulation of a typical Download → WriteFile → Execute flow with the ETW agent that we are about to write in the background:
notion image
The demo Powershell script uses WebClient to download a popular SSH client putty.exe, after which starts the downloaded program with & command:
$WebClient = New-Object System.Net.WebClient $DesktopPath = [Environment]::GetFolderPath("Desktop") $WebClient.DownloadFile("https://the.earth.li/~sgtatham/putty/latest/w64/putty.exe","$DesktopPath\q.exe") & $DesktopPath\q.exe
If you were to run the Powershell commands above in your Powershell ISE, you would see a Putty interface. But since the demo is running an ETW based agent that denies downloaded file, we get that “Access is denied” message. So what is this Access Control List rule?
👉🏻
Right-click Properties → Security tab → Advanced button → Add button → Select a principal (Use Everyone) → Show Advance permissions → Select Type Deny → Clear all → Select only Traverse folder / Execute file → OK
This creates the SAME OUTCOME like the demo except this is done manually with UI.
notion image
ACLs are stored in the part of an NTFS partition that does all the background plumbing - the MFT (Master File Table). The ACL does not follow a file around, since it is not a part of the file (just like the filename it is metadata). Notice the initial download done by line 3 starts with a generic EXE icon because it takes a while to retrieve file contents due to network latency. At that initial file creation juncture, the background ETW agent successfully added this special permission ACE programmatically, even when it is still in the middle of downloading. We’ll get ChatGPT to show us how it’s done programmatically later! There is NO file analysis that can be denied by holding an exclusive file-lock like some malware authors do to deny certain host sensors.
💪🏻
This is a good time to get hands-on with ETW. I will answer Will it affect legit software operations & deployments? towards the end of this sharing.

What do I need to get started with ETW?

  1. Read excellent ETW notes from https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101, especially the section on Consuming Events via Code so as to install the Microsoft TraceEvent package.
  1. Visual Studio Community Edition running off Win 10 Home or Pro
  1. Sign up ChatGPT

Create a C# .NET Core Console Project

  • Run Visual Studio CE as admin (necessary for starting ETW trace)
  • Install Microsoft TraceEvent package for your new project
  • Edit Program.cs & replace with the following (see my comments within):
using System; using System.IO; using System.Security.AccessControl; using System.Security.Principal; using Microsoft.Diagnostics.Tracing.Parsers; using Microsoft.Diagnostics.Tracing.Session; namespace ConsoleAppETW { class Program { static void Main(string[] args) { using (TraceEventSession session = new TraceEventSession("MyFileCreateTracer")) { // we are using Kernel Provider NOT Sysmon session.EnableKernelProvider(KernelTraceEventParser.Keywords.DiskFileIO); // interested only with FileIOFileCreate session.Source.Kernel.FileIOFileCreate += Kernel_FileIOFileCreate; // start the trace session.Source.Process(); } } private static void Kernel_FileIOFileCreate(Microsoft.Diagnostics.Tracing.Parsers.Kernel.FileIONameTraceData obj) { try { // interested with files, not directories if (Directory.Exists(obj.FileName)) { Console.WriteLine(obj.FileName + " | It's directory!"); return; } // get owner string FileSecurity fileSecurity = new FileInfo(obj.FileName).GetAccessControl(); IdentityReference sid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = sid.Translate(typeof(NTAccount)) as NTAccount; string owner = ntAccount.Value; Console.WriteLine(obj.FileName + " | owned by " + owner); } catch // GetAccessControl can throw exceptions when denied by Windows { } } } }
  • Build project & Run. It should look something similar:
    • notion image

Add an Access Rule Programmatically

Since everyone is crazy about ChatGPT, here you go:
notion image
  • Modify your eariler console program’s Kernel_FileIOFileCreate such that it will add this access rule when file is NOT owned by NT SERVICE\TrustedInstaller, NT AUTHORITY\SYSTEM or BUILTIN\Administrators.
ℹ️
NTFS file ownership is designed in such a way that only processes with “Take ownership of files or other objects user” right (SeTakeOwnershipPrivilege) can take ownership of a file (e.g. processes started by local admin with UAC or Domain Admin). When we deny PE by monitoring FileCreate (add ACL rule), ProcessCreate & ImageLoad (kill process) to deny execution, attacker’s need to escalate to run or persist a PE based malware or backdoor! We have effectively increased the cost of infiltration & persistence with a cheap defense at our end.
  • For those who are adventurous, install Sysmon, use the correct Provider for Sysmon, modify the codes… or just ask ChatGPT again!
    • notion image

Will it affect legit software?

Any software written that are owned by SYSTEM, TrustedInstaller & BUILTIN/Adminstrators (e.g. Windows updates, Program Files..) are NOT affected. Files written prior to the start of this ACL disruption would still run. Suppose we also check file ownership for ProcessCreate & ImageLoad, executable files regardless if it is “good” or “bad” will be denied (process killed) so long the file owner is not any of those 3 stated earlier.
notion image
 
Notice the 1st folder with a bunch of numbers like some kind of versioning? Every OneDrive update will create yet another such folder. Other apps also are deployed similarly. A couple of ways to fix such weak file ownership:
  1. Use centralised software deployment that deploys into Program Files such that it is owned by BUILTIN\Administrators
  1. Retroactively adjust file ownership with elevated Powershell command (e.g. GPO computer startup script option, or equivalent):
# the target file gets ownership + ACL from cmd.exe get-acl c:\windows\system32\cmd.exe | set-acl c:\targetDirectory\whateverLegit.exe
So it’s really back to the earlier hypothetical question that highlights the risk: when users can modify executable files, so can attackers! Why take that risk?
☁️
Given many apps are mostly subscription-based services running off the cloud, there are typically not many native apps unless they need to take advantage of some hardware features like video & audio conferencing. It will be worthwhile to enumerate all program files with weak ownership as part of endpoint hygiene assessment.

What about NON-PE based Code-Execution?

notion image
By making life harder to launch written PE, we are cornering adversaries to use NON-PE approach. But why?
🧠
The set of system tools that can be abused is a MUCH SMALLER set than the infinite Portable Executables set that attackers can churn out. Also, within the set of system tools that are commonly abused, some system tools are NOT really used or irrelevant to your environment!
A quick recap of my Code-Execution mental model shared in another series. There are only 3 types of Code-Execution to Divide & Conquer!
notion image
By NON-(written)-PE approach, we are referring to Type 2 & 3. Exploits (Type 3) are typically favored when there are exposed vulnerabilities that attackers can scan to pick the correct exploit to use (e.g. recent MS Exchange flaws, Log4J & so on). For client zone that are not directly exposed but can still egress to Internet, we are left with Type 1 files that already existed earlier than App-Control, & Type 2 techniques that can undo the ACL rule since the file is still owned by any user’s process (has full access control). Checking ownership for (Sysmon + ETW) ProcessCreate & ImageLoad will handle these two scenarios (Sysmon allows filtering away Microsoft signed DLLs, checking each & every DLL with ETW Kernel Provider equivalent will likely impact system performance).
🧠
For any initial loading technique that is aware of this ACL rule & undoing it, we can infer that this is a very targeted attack. The exercise of programmatically adding ACL to a file had already equipped you to add specific audit rules that allow your backend to be alerted of such attempts. Hint: Event IDs 4656 & 4670.

What’s Next?

I will cover a hands-on series with Free Endpoint Defense & Response, focusing on disrupting Type 2:
  • Convert a simple web chat client-server program into a backdoor
  • Use FreeEDR to observe what’s going on with this DIY backdoor
📢
Join my Telegram group https://t.me/+iWZ6l-x5jGE1ZDc9 & be notified of new contents!

Further Reading