Hunting service execution from user-writable directories with Tanium

Hunting service execution from user-writable directories with Tanium

Important:

Validated against: TODO - confirm Core Content / Index / Threat Response content versions before publish.

A Windows service that runs as NT AUTHORITY\SYSTEM and launches its binary out of a directory standard users can write to is a complete privilege escalation. Replace the file, wait for a restart, and your code runs as SYSTEM. There is no CVE, no patch, and no alert, because nothing is broken. The permissions are just wrong.

Six questions take you from the whole service population down to who last rewrote a service's path, with two things worth settling before any of them: how the escalation actually works, and which directories deserve a permission read at all. Nothing below explains what a sensor does or how to stack a result grid. One note on the syntax. This deployment answers through Tanium Atlas, so each step carries its question in prose followed by the Tanium question syntax Atlas generated for it. That syntax is what names the sensors behind the data, and it is what you adapt if you are building in the question builder.

The hard part of this hunt is not finding the services. It is being able to say, with confidence, that a directory is writable by ordinary users. That is where most of this guide goes.

Key takeaways

  • A service whose binary sits in a directory granting write access to BUILTIN\Users or NT AUTHORITY\Authenticated Users can be hijacked by replacing the binary and triggering a restart (T1574.010). The service account it runs under is the privilege the attacker gets.

  • The exposure is almost always third-party or in-house software installed outside C:\Program Files, because the protected Windows locations already have correct ACLs and installers writing elsewhere frequently do not.

  • Volume is the normal result, not a sign you asked wrong. A first pass across a real estate returns far more than you can triage as alerts, which is why the deliverable is a ranked exposure list rather than a queue.

  • Service names are not a stable grouping key. Installers inject per-installation identifiers, so one product deployed widely arrives as many distinct-looking services. Group on the directory, not the service name.

  • Permission output is one access control entry per row, in the form PRINCIPAL (flags), and the flags include inheritance markers. NT AUTHORITY\SYSTEM (OI)(CI)(F) is a single entry carrying Object Inherit, Container Inherit and Full Control.

  • Principal names come back localized. A German-locale host reports VORDEFINIERT\Administratoren where an English one reports BUILTIN\Administrators, so a filter written against the English strings silently skips those endpoints.

  • Two questions establish the finding: enumerate services with their paths and accounts, then read the ACL on the parent directory. Both are current-state reads that need no collection configured in advance.

  • Current state cannot tell you whether a writable path was always writable or was opened up last Tuesday. Trace Registry Keys or Values covers half that gap by naming the process and account that rewrote a service's ImagePath, as far back as Recorder retention allows.

Prerequisites

Requirement

Detail

Platform

Windows. Service Status with Hash and Trace Registry Keys or Values are Windows-only; their scripts on Linux, macOS, Solaris and AIX are non-functional stubs. Path Permissions and Folder Exists do run on all five, so the permission half of this hunt travels even though the service half does not.

Content

Core Content for Path Permissions and Folder Exists, Incident Response for Service Status with Hash, Index for Index - File Details, Threat Response for Trace Registry Keys or Values.

Module

Tanium Index deployed and indexing the directories you care about, for Step 5. Tanium Threat Response with a Recorder configuration capturing registry events, for Step 6. Steps 1 to 4 need neither.

RBAC

The platform READ_SENSOR privilege plus the content sets above. Content-set scoping decides what a given operator sees, which is worth knowing when two analysts compare results.

Recorder lookback

Step 6 can only see as far back as your Recorder retention. Whichever of the size and age limits comes first is your ceiling.

Not covered here: macOS and Linux service permissions, the remediation itself, and building a Threat Response Signal around this behavior.

Why a writable service directory is a privilege escalation

When Windows starts a service it reads the service's configuration from HKLM\SYSTEM\CurrentControlSet\Services\<ServiceName>, takes the ImagePath value to find the executable, and launches it under the account named in ObjectName. Nothing in that sequence validates who was able to write the file.

How a writable service directory becomes a privilege escalation

Service configured under HKLM\SYSTEM\CurrentControlSet\Services

ImagePath names C:\VendorApp\agent.exe

Can BUILTIN\Users write to C:\VendorApp?

No

Yes

Service restarts: reboot, manual, or auto-start

Attacker code runs as the service account

Binary is protected.

Expected state.

Any logged-in user replaces agent.exe

How a writable service directory becomes a privilege escalation.

The privilege the attacker gains is whatever the service already had. A service running as NT AUTHORITY\SYSTEM from a writable directory hands over the machine. One running as NT AUTHORITY\LocalService hands over much less. Both are worth fixing; only one is worth waking someone up for, and that distinction is what turns a long result set into a priority order.

Permissions are reported as access control entries, one per row, and reading them correctly is the whole skill. The flags that matter:

Flag

Meaning

Significance here

(F)

Full Control

Write, delete, and change permissions. The strongest finding.

(M)

Modify

Write and delete. Enough to replace a binary, so it is equivalent for this hunt.

(W)

Write

Enough to replace a binary in many configurations. Check alongside (M).

(RX)

Read and Execute

Expected for a service directory. Not a finding.

(OI)

Object Inherit

The entry propagates to files in the folder, which is what makes it reach the binary.

(CI)

Container Inherit

The entry propagates to subfolders.

(I)

Inherited

This entry came from the parent, not from an explicit grant here.

(OI) and (CI) are the two most commonly missed, because they appear between the principal and the permission letter and a naive filter written as Users.*\(M\) will still match while a filter written as Users \(M\) will not. A real entry looks like BUILTIN\Users (OI)(CI)(M).

The principals worth flagging are BUILTIN\Users, NT AUTHORITY\Authenticated Users, Everyone, and NT AUTHORITY\INTERACTIVE. The ones that are expected are NT AUTHORITY\SYSTEM, BUILTIN\Administrators, CREATOR OWNER, and NT SERVICE\TrustedInstaller.

Choosing which directories to hunt

Path Permissions takes one exact directory and offers no wildcard, so Steps 3 through 6 each run against a single path you supply (<DirectoryPath> below stands in for it). That constraint sets the agenda: checking a directory is trivial, and choosing the directories is the actual work.

Three ways to build that list.

Derive them from the service inventory. This is the main route and it is Steps 1 and 2. Enumerate every service, keep the ones whose binary sits outside the protected Windows locations, reduce each path to its top-level directory, and the estate has handed you its own candidate list. Everything else in this section is a way to order it.

Take the shapes that are reliably wrong. Custom folders at a drive root (C:\VendorName\, C:\Tools\, C:\Scripts\), anything on a secondary volume, and backup or monitoring agents installed outside Program Files are the recurring offenders, because installers that place software there frequently set permissions for convenience during troubleshooting and never tighten them. Directories named for automation are worth checking first: a folder created so that a team could drop scripts into it is a folder created to be writable.

Invert the prevalence. After Step 2 you have a count of endpoints per directory. Both ends of that distribution are interesting for different reasons. A directory on almost every endpoint is a standard build component, so a permission problem there is your largest exposure by blast radius. A directory on one or two endpoints is either a bespoke installation or something that should not be there, and it is the cheaper thing to investigate.

All three routes converge on the same test, which Step 4 performs: is this directory writable by ordinary users? Where the answer is yes and the service there runs as SYSTEM, that directory goes to the top of the list.

Every question below needs the platform READ_SENSOR privilege, and content-set scoping means your results may be narrower than a colleague's.

Step 1: enumerate every service and its binary path

Start with the whole population. One sensor carries the service name, the path, the account and the binary hash together, which is what makes it the right starting point, because the alternatives split path and account across sensors that do not join cleanly.

Ask: Using the "Service Status with Hash" sensor with the SHA256 hash type, list Windows services with their Command Line and Service Account.

Get "Service Status with Hash"["SHA256"] from all machines with "Is Windows" equals "True"

Returns Short Name, Long Name, Status, Service Account, Command Line and Hash. Command Line is the ImagePath as configured, so it carries quoting and trailing arguments: "C:\VendorApp\agent.exe" --service is one value, and the path you want is the quoted portion. Parse the executable out before you group on it.

The result arrives grouped. Identical rows collapse across endpoints and carry a Count, so what you get is a prevalence view of distinct service configurations rather than one row per endpoint. That is the shape you want here, since the question you are asking is which service configurations exist and how common they are, but it means a Count of 1 is a configuration unique to a single endpoint, not a single service.

The hash column populates for binaries the sensor can read and hash at query time. Treat hash coverage as a bonus on third-party and custom binaries, which is where this hunt looks anyway, rather than as a complete inventory.

Two scope facts. The sensor caches for 600 seconds, so a read can predate a service change by up to ten minutes. And it enumerates services from Win32_Service, which does not include services that have been deleted. This is a current-state question, and Step 6 is how you ask about the past.

On a large fleet this returns a lot. That is the point, and Step 2 is what makes it tractable.

Step 2: rank the directories, not the services

Do not triage the service list. Reduce it to a directory list first, because the directory is the unit of exposure: one bad ACL on C:\VendorApp covers every service and every binary inside it, and fixing it once fixes all of them.

Two things get in the way of a clean count.

Service names are not a grouping key. Installers routinely append a per-installation identifier to the service name, so one product deployed across an estate arrives as many services with different Short Name values and the same directory. Grouping on the service name turns a single finding into hundreds. Group on the top-level directory instead and the picture collapses to something you can read.

You can do most of this in the platform. Stack the Step 1 results on Command Line and the distinct configurations are already counted for you. Where you need to go further is reducing a full path to its top-level folder, which the result grid will not do. Export and normalize:

import pandas as pd STANDARD = r'(?i)^[a-z]:\\(windows|program files( \(x86\))?|programdata)\\' df = pd.read_csv("service_status.csv") # Strip quoting and trailing service arguments, keep the executable path df["Path"] = df["Command Line"].str.extract(r'^"?([a-zA-Z]:\\[^"]+?\.exe)"?', expand=False) # Drop the protected Windows locations df = df[df["Path"].notna() & ~df["Path"].str.contains(STANDARD, regex=True, na=False)] # Reduce to the top-level directory and normalize the drive letter df["TopFolder"] = (df["Path"].str.extract(r'(?i)^([a-z]:\\[^\\]+)', expand=False) .str.replace(r'^([a-z]):', lambda m: m.group(1).upper() + ':', regex=True)) ranked = (df.groupby("TopFolder") .agg(services=("Short Name", "nunique"), endpoints=("Count", "sum"), system=("Service Account", lambda s: s.str.contains("SYSTEM", case=False).any())) .sort_values(["system", "endpoints"], ascending=[False, False]))

ranked is your working list, and the ordering is the deliverable. Directories hosting a SYSTEM service come first; within that, prevalence decides. Everything from here runs one directory at a time.

Step 3: confirm the directory's footprint

Before spending permission reads, establish where the directory actually exists. This is cheap and it catches the case that matters most.

Ask: Using the "Folder Exists" sensor, how many Windows endpoints have the folder <DirectoryPath>?

Get "Folder Exists"["C:\VendorApp"] from all machines with "Is Windows" equals "True"

Returns a single Folder Exists column whose value is either Folder Exists: <path> or Folder does not exist, grouped with a count. Quote the path inside the brackets, because the drive-letter colon breaks the parser unquoted, and single backslashes are fine inside the quotes.

The useful comparison is against Step 1. A directory that exists on materially more endpoints than run the service is worth a second look: it means leftover installations, a partially removed product, or a folder staged ahead of the service that will use it. A directory that exists on fewer endpoints than report the service means the service is configured to launch something that is not there.

The sensor caches for 600 seconds and runs on Windows, Linux, macOS, Solaris and AIX.

Step 4: read the access control list

This is the question the hunt exists to ask.

Ask: Using the "Path Permissions" sensor, what are the file system permissions on the folder <DirectoryPath> on Windows endpoints?

Get "Path Permissions"["C:\VendorApp"] from all machines with "Is Windows" equals "True"

Returns a single Path Permissions column. One access control entry per row, in the form PRINCIPAL (flags), grouped with a count of how many endpoints carry that entry. On Windows the sensor reports what icacls reports; on the Unix platforms it reports the mode bits instead, in a different format, so a filter written for one will not read the other.

What you are looking for is any row whose principal is BUILTIN\Users, NT AUTHORITY\Authenticated Users, Everyone or NT AUTHORITY\INTERACTIVE carrying (F), (M) or (W).

Four things change what you see.

Reassemble the ACL yourself. Because the grouped view is per-entry, no single row tells you a directory's full permission set, and a dangerous entry present on three endpoints sits in the same result as the benign entries present on all of them. Compare entry counts against the Step 3 footprint: an entry appearing on a subset is drift, and drift is usually the interesting part.

Match the flags loosely and the principal exactly. Inheritance markers sit between the principal and the permission letter, so match on the principal and then look for the permission letter anywhere in the flag group. BUILTIN\Users (OI)(CI)(M) and BUILTIN\Users (M) are both findings.

Principal names are localized. A German-locale endpoint reports VORDEFINIERT\Administratoren and NT-AUTORITÄT\SYSTEM. Any filter written against the English principal names will skip every non-English host in the estate, and it will do so silently, because those endpoints still return rows. Either build the locale variants into your filter or normalize on the well-known SID instead of the display name. In a multinational estate this is not an edge case.

A missing path reports as a permission value. Endpoints where the folder is absent or unreadable return Unable to get permissions or does not exist in the same column as real entries. Exclude that string before you count anything.

The sensor caches for 900 seconds, longer than the service sensor, so on an endpoint that changed recently the two reads can disagree.

Step 5: confirm the binary

Once a directory is confirmed writable, look at what is actually in it. This is the step that separates "the door is unlocked" from "somebody has been through it".

Ask: Using the "Index - File Details" sensor, list executable files in the directory <DirectoryPath> on Windows endpoints, sorted by Last Modified descending.

Get "Index - File Details"["100","C:\VendorApp","*.exe","*","*","*","*","*","*","0","0","Last Modified","Descending"] from all machines with "Is Windows" equals "True"

Thirteen positional parameters, and the order is not the one you would guess. The row limit is first, not last; the directory, filename, size, magic number and four hash fields follow; then two checkboxes; then the two sort fields. * means unconstrained, and at least one search field has to be something other than *.

Returns Directory Path, File Name, Object Type, Size (Bytes), Created, Last Modified, Last Hashed, Magic Number (First 4 bytes), and the four hash columns.

Timestamps are relative buckets by default. The eleventh parameter is useExactTimestamps, and at 0 you get <1 week ago and <1 month ago rather than dates. That is fine for spotting an outlier and useless for building a timeline. Set it to 1 when you need to correlate a modification against anything else.

Stack on SHA256 Hash. A binary that is identical across the estate and one that differs on a single endpoint look the same by filename and completely different by hash, and the single-endpoint outlier is the one to pull. Magic Number (First 4 bytes) of 4d5a9000 confirms a PE file regardless of what the extension claims.

Which hash columns populate depends on your Index configuration. Check what yours computes before building a workflow on a column that is empty in your environment.

This step is collection-gated. Index reports on paths it has indexed. An endpoint with no Index coverage of the directory does not appear in the results, and that absence is not the same as the directory being clean. Confirm your Index configuration covers the paths you are hunting before reading anything into a short result.

Step 6: find out who changed it

Everything so far is current state. It tells you the trap is set, not that anyone set it deliberately or recently. Registry history is what closes that gap.

The Trace Registry Keys or Values sensor ships a Service Imagepath Changes common-use parameter set, which is the same question pre-filled. Name it if you are pointing a colleague at this; the syntax below is the same thing spelled out.

Ask: Using the "Trace Registry Keys or Values" sensor, show registry SetValue operations against ImagePath under HKLM\SYSTEM\CurrentControlSet\Services on Windows endpoints in the last week, with up to 100 results per host and stacking turned off.

Get "Trace Registry Keys or Values"["1 week","","0","0","100","0","HKLM\SYSTEM\CurrentControlSet\Services","ImagePath","SetValue","","",""] from all machines with "Is Windows" equals "True"

Twelve positional parameters, every one present, in definition order: time range, absolute time range, treat-input-as-regex, output-yes-or-no, max results per host, make-stackable, key path, value name, operation, process path, domain, username. Returns Endpoint Name, Timestamp (UTC), Key, Value, Operation, Process Path, Domain and Username.

Three parameter values decide whether this question answers anything.

MaxResultsPerHost is position 5 and defaults to 1. At the default you get one event per endpoint and no idea how many you missed. It is set to 100 above.

MakeStackable is position 6 and defaults to 1. At the default the sensor strips the endpoint name, username and timestamps so results collapse into prevalence counts, which is the opposite of what you want here, because the endpoint, the account and the time are the finding. It is set to 0 above for one row per event.

The operation vocabulary is fixed: Create, SetValue, Delete, Rename, PermissionsChanged. SetValue is the one that catches an ImagePath being rewritten. A value outside that set matches nothing and returns no error.

Process Path is the answer you came for. A service path rewritten by an installer running from a temp directory is one story; the same value rewritten by a shell is another. Correlate the timestamp against Step 5's exact modification times and you have the sequence.

This step is collection-gated too, and more sharply than Step 5. Trace reads Recorder data, so it requires Threat Response with registry event collection enabled, and your lookback is bounded by Recorder retention. The sensor reports Search complete, no matches when it ran and found nothing. That is a real answer within your retention window, and it is not the same as the events never having happened.

What this hunt does and does not establish

It establishes that a service configured to run under a given account launches a binary from a directory whose ACL grants write access to a group ordinary users belong to. That is a real, exploitable exposure and it does not require any evidence of an attacker to be worth fixing.

It does not establish compromise. Almost everything this hunt returns will be third-party software installed carelessly, and the finding is a hygiene finding. Treat it as exposure to be prioritized and reduced, not as a queue of alerts, or you will burn your credibility on the first pass and the volume will bury you.

It does not prove the writable window is new. Steps 1 through 5 are point-in-time reads. Step 6 can tell you when an ImagePath was rewritten, but nothing here tells you when a directory's permissions were set, and a directory that has been writable since installation looks identical to one that was opened up last week.

It does not cover services whose ACL problem is on the binary rather than the folder, services that load a DLL from a writable path while the executable itself is protected, or the same weakness on scheduled tasks. Those are the same technique through different doors and they need their own questions.

Finally, Path Permissions reads the ACL, not the effective access. Group membership, deny entries and privilege assignments can all make the practical answer different from the one the entry list implies. For a directory you are about to escalate, confirm effective access on a representative endpoint before you write it up.

Next steps

Take the ranked directory list from Step 2 and work down it. For each directory: footprint it (Step 3), read the ACL (Step 4), and stop there unless a non-privileged principal has write access. For the ones that do, add the service account from Step 1, and the ordering of your report writes itself: SYSTEM services in writable directories at the top, everything else below.

Deliver it as exposure with a priority order rather than as findings. A security team can work down a ranked list and report progress against it. That framing is what carries a hygiene result into a risk register, which is the subject of the companion post.

Further reading

About the author

Ryan Creecy is a Threat Hunter at Tanium, where he builds detection content and runs hunt engagements across customer environments. He develops the HuntIQ tooling the hunting team uses to track engagement state and detection coverage.