Run Command (Package)
Two Tanium packages that run one command that the operator types, after a set of checks:
- Run Command (Windows) runs the command in Windows PowerShell 5.1 as SYSTEM.
- Run Command (Linux and macOS) runs the command in bash as the Tanium client user, normally root.
This is a break-glass tool. Use it when no dedicated package fits and you must run something on a group of endpoints now. The package runs whatever is typed, so the access control around it matters more than the script.
The packages have an Audit mode. Audit mode runs the checks and reports whether the command would run. It runs nothing.
The packages do not restart the endpoint unless the command does. The checks stop a shutdown or a power off. A restart is allowed.
Restrict this to a locked-down content set
The real control on this package is who can deploy it. Put it in its own content set. Give deploy rights to a few senior operators through RBAC. Never target an open group such as All Computers. The checks inside the scripts stop common mistakes. They are not a security boundary, and a person who wants to get around them can. Do not loosen deploy rights because the checks exist.
Test status
Tested through Tanium on one Windows endpoint and one Linux endpoint: Audit and Run mode, blocked commands, exit codes, special characters in the command, and the 60-line limit in the action log. The power-off check was added after the lab tests and was tested outside Tanium only. Not tested: macOS, and endpoints with CrowdStrike or CyberArk installed. Deploy to one endpoint first and read the action log.
What the package does
- Reads Mode and Command, and decodes the command. Tanium sends both values URL-encoded.
- Stops with exit code 2 when a parameter is incorrect. For example, the command is empty, or it is not valid PowerShell.
- Runs the checks. When a check trips, the package logs
BLOCKEDwith the reason and stops. Nothing runs. - In Audit mode, logs
WOULD RUNand stops. Nothing runs. - In Run mode, runs the command and writes its output to the action log.
- Logs the result and ends with an exit code. See Exit codes.
What the checks stop
| Category | What happens |
|---|---|
| Delete a protected system path | Blocked. On Windows: the Windows folder, boot and recovery folders, the root of each drive, the root of Program Files and Users, protected registry keys, and admin shares. On Linux and macOS: system folders such as /etc, /usr, /boot, /var/lib, and the roots of /home, /root, /opt, /var. Cleanup folders such as C:\Windows\Temp and /usr/local are allowed. |
| Delete with a path that the script cannot read | Blocked. For example, a path built from a variable. |
| High-damage disk, boot, or registry operation | Blocked. Disk format, partition changes, shadow-copy or backup deletion, boot configuration deletion, raw disk writes. |
| Shut down, power off, hibernate, or suspend | Blocked, because Tanium cannot start the endpoint again. A restart is allowed. |
| Stop, disable, uninstall, or delete a security agent | Blocked for CrowdStrike, Tanium, and CyberArk, also when the agent folder or registry key is the target. Reading the status of these agents is allowed. |
| Encoded or decode-and-run command | Blocked. On Windows: a PowerShell encoded command, and Invoke-Expression. On Linux and macOS: text that is decoded and sent to a shell. |
The checks are a list of known patterns. Anything that is not on the list runs. The Windows checks read the command through the PowerShell parser. The Linux and macOS checks have no parser and are weaker.
Requirements
- Windows: Windows PowerShell 5.1 and the Tanium Client.
- Linux and macOS: bash and the Tanium Client.
- A Tanium account with permission to create packages in a content set and deploy actions. The content set must be restricted to a small group.
Create the packages
- In the Tanium Console, go to Administration > Content > Packages.
- Click Create Package.
- Fill in the fields with the values in the tab for the package. Then add the file and the parameters.
| Field | Value |
|---|---|
| Package Name | Run Command (Windows) |
| Display Name | Run Command (Windows) |
| Description | Runs one PowerShell command that you type, as SYSTEM, for break-glass work when no other package fits. Checks the command first and refuses it when it deletes a protected Windows folder or registry key, formats a disk, deletes shadow copies or boot settings, shuts down the endpoint, stops or removes CrowdStrike, Tanium, or CyberArk, or uses an encoded command. Audit mode runs the checks, reports the result, and runs nothing. The checks prevent accidents and are not a security boundary. The command is written to the action log as typed. Windows only. |
| Content Set | Your custom content set. Use a content set that only a few senior administrators can deploy. |
| Command | cmd.exe /d /c powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -NonInteractive -NoProfile -File RunCommand.ps1 "$1" "$2" |
| Command Timeout | 15 minutes |
| Download Timeout | 10 minutes |
| Ignore Action Lock | Clear (not selected) |
| Launch this package command in a process group | Selected |
| Files | RunCommand.ps1 |
Parameters:
| Key | Type | Label | Values | Default |
|---|---|---|---|---|
$1 |
Drop-Down List | Mode | Audit first, then Run |
None. An empty value counts as Audit. |
$2 |
Text Input | Command | Any PowerShell command | None. The operator must enter a value. |
Help text:
| Key | Help text |
|---|---|
$1 |
Audit runs the safety checks and reports the result. It runs nothing. Run runs the command if the checks pass. |
$2 |
The PowerShell command to run as SYSTEM, for example Get-Service -Name wuauserv. The action log shows it as typed, so do not type a password. |
| Field | Value |
|---|---|
| Package Name | Run Command (Linux and macOS) |
| Display Name | Run Command (Linux and macOS) |
| Description | Runs one bash command that you type, as the Tanium client user (normally root), for break-glass work when no other package fits. Checks the command first and refuses it when it deletes a protected system folder, writes to a raw disk, shuts down the endpoint, stops or removes CrowdStrike, Tanium, or CyberArk, or decodes and runs hidden text. Audit mode runs the checks, reports the result, and runs nothing. The checks prevent accidents, are weaker than the Windows checks, and are not a security boundary. The command is written to the action log as typed. Linux and macOS. |
| Content Set | The same restricted content set. |
| Command | /bin/bash runcommand.sh "$1" "$2" |
| Command Timeout | 15 minutes |
| Download Timeout | 10 minutes |
| Ignore Action Lock | Clear (not selected) |
| Launch this package command in a process group | Selected |
| Files | runcommand.sh |
Parameters:
| Key | Type | Label | Values | Default |
|---|---|---|---|---|
$1 |
Drop-Down List | Mode | Audit first, then Run |
None. An empty value counts as Audit. |
$2 |
Text Input | Command | Any bash command | None. The operator must enter a value. |
Help text:
| Key | Help text |
|---|---|
$1 |
Audit runs the safety checks and reports the result. It runs nothing. Run runs the command if the checks pass. |
$2 |
The bash command to run as root, for example systemctl status sshd. The action log shows it as typed, so do not type a password. |
- Click Save.
- Do steps 2 to 4 again for the second package.
Changed a script later?
Tanium keeps its own copy of each uploaded file. After you change a script, edit the package and upload the file again.
Deploy the package
Deploy the package two times on one endpoint first. Use Audit mode first. Then use Run mode.
Run 1: Audit
- In the Tanium Console, go to Interact.
-
In the question bar, type this question. Replace
ENDPOINT-01with the name of your endpoint. -
Press Enter.
- Select the endpoint.
- Click Deploy Action.
- In the Deployment Package field, type
Run Command. SelectRun Command (Windows)orRun Command (Linux and macOS). - Set Mode to
Audit. - In Command, type the command.
- Click Show preview to continue.
- Make sure that the list shows the correct endpoint.
- Click Deploy Action.
- Read the action log. Refer to Read the results.
- Make sure that the log shows
WOULD RUN.
Run 2: Run
- Deploy the package again to the same endpoint.
- Set Mode to
Run. - Type the same command.
- Click Show preview to continue.
- Click Deploy Action.
- Read the action log. Make sure that it shows
RANand the output that you expect.
When the result is correct, deploy to the group that needs it. For a group of one operating system, use a filter such as Is Windows equals True or Is Linux equals True.
Exit codes
| Code | Meaning |
|---|---|
| 0 | Finished. Run mode: the command ran and returned 0. Audit mode: always 0. Read the BLOCKED or WOULD RUN line. |
| 1 | The command ran and failed. It returned a code that is not 0, or it stopped with an error. The FAILED line shows the command's own code. |
| 2 | A parameter was incorrect: Mode, an empty command, a split value, or a Windows command that is not valid PowerShell. Nothing ran. |
| 3 | Blocked: a protected system path, a high-damage disk, boot, or registry operation, or a shutdown. Nothing ran. |
| 4 | An error occurred that the package did not expect. Nothing ran. Read the action log. |
| 5 | Blocked: a protected security agent. Nothing ran. |
| 6 | Blocked: an encoded or decode-and-run command. Nothing ran. |
Action History shows Completed for every exit code, also for a blocked command. The status only says that the package command started. Read the exit code in the last line of the action log, Action Exit Code: N.
Some programs, such as robocopy, use codes that are not 0 for success. The package returns 1 for these. Read the code in the FAILED line.
Read the results
To read the action log from the Tanium Console:
- Go to Interact.
-
Type this question. Replace
<action ID>with the ID of your action. -
Press Enter.
Each run starts with a started on line and a Settings: line, and ends with a Summary line and a Finished with exit code line. Between them, the result line starts with one of these words:
| Word | Meaning |
|---|---|
WOULD RUN |
Audit mode only. The checks passed. Run mode would run the command. |
BLOCKED |
A check stopped the command. The line shows the reason. Nothing ran. |
WRONG INPUT |
A parameter was incorrect. Nothing ran. |
RUNNING |
Run mode. The checks passed. The command output follows. |
RAN |
The command returned exit code 0. |
FAILED |
The command returned another code, or stopped with an error. |
TRUNCATED |
The output had more than 60 lines. The action log shows the first 60. |
The action log shows the first 60 lines of the command output, and drops blank lines, so the result stays on screen. The package writes every line, with up to 5000 lines of output, to a log file on the endpoint:
- Windows:
C:\Windows\Temp\RunCommand.log - Linux and macOS:
/var/log/runcommand.log, when the client user can write there.
On Windows, each line has a level such as [INFO] or [WARN]. On Linux and macOS, warnings and errors start with WARNING: or ERROR:. Each line also starts with the date and time. The Tanium Console shows one space after the first word of a line, and table output loses its column alignment. Add | Format-List to a PowerShell command when the output is a table.
Example log: Audit, blocked (Windows)
[INFO] ===== RunCommand 2.0.0 started on ENDPOINT-01 =====
[INFO] Settings: mode=Audit; command=Remove-Item -Path "C:\Users" -Recurse -Force
[WARN] BLOCKED command deletes 'C:\Users', a protected OS path.
[INFO] Summary (Audit, nothing changed): would run=0; blocked=1
[INFO] ===== Finished with exit code 0 =====
Example log: Run (Windows)
[INFO] ===== RunCommand 2.0.0 started on ENDPOINT-01 =====
[INFO] Settings: mode=Run; command=whoami
[INFO] RUNNING the checks passed. Output follows.
nt authority\system
[INFO] RAN the command returned exit code 0.
[INFO] Summary (Run): ran=1; failed=0
[INFO] ===== Finished with exit code 0 =====
Example log: Run, failed (Linux)
===== runcommand 2.0.0 started on ENDPOINT-02 =====
Settings: mode=Run; command=ls /nonexistent_xyz_123
RUNNING the checks passed. Output follows.
ls: cannot access '/nonexistent_xyz_123': No such file or directory
ERROR: FAILED the command returned exit code 2.
Summary (Run): ran=1; failed=1; command exit code=2
===== Finished with exit code 1 =====
Troubleshooting
| Log message | Cause | Action |
|---|---|---|
BLOCKED command deletes '<path>', a protected OS path. |
The command deletes a path on the protected list. | Check the path. If the target is correct, use a dedicated package for that cleanup. |
BLOCKED ... a path built from a variable ... |
The delete path is built from a variable, so the script cannot check it. | Deploy again with the full path typed in the command. |
BLOCKED command targets a protected security agent ... |
The command stops, disables, uninstalls, or deletes CrowdStrike, Tanium, or CyberArk. | Use the vendor's own process for that agent. |
BLOCKED command shuts down, powers off, or hibernates the endpoint. ... |
The command would turn the endpoint off. Tanium cannot start it again. | Deploy again with a restart command. The log line names one. |
WRONG INPUT Mode must be Audit or Run. Got: <value>. Nothing ran. |
The Mode value is not on the list. | Edit the package. Make sure that the Mode values are Audit and Run. |
WRONG INPUT the command is empty. Nothing ran. |
The Command box was empty. | Deploy again with a command. |
WRONG INPUT input did not parse cleanly as PowerShell (...) |
Windows only. The command is not valid PowerShell. For example, it uses cmd syntax with &. |
Deploy again with the command corrected. For cmd syntax, start the command with cmd /c and put the rest in double quotes. |
WRONG INPUT the script received 3 values instead of 2. ... |
The package command line is wrong, so the command was split. | Edit the package. Make sure that the command line ends with "$1" "$2". |
TRUNCATED the action log shows the first 60 of 200 output lines. ... |
The command printed more than 60 lines. | Deploy again with a command that prints less, or that filters its output. |
FAILED the command stopped with an error: <message> |
Windows only. A PowerShell error stopped the command. The package stops at the first error. | Read the message. Correct the command and deploy again. |
No Finished with exit code line |
The command ran longer than the command timeout, and Tanium stopped it. | Increase the command timeout. Then deploy again. |
Things to know
- Parameters arrive URL-encoded. Tanium encodes each character that is not a letter or a digit. For example, a space arrives as
%20and-arrives as%2d. The script decodes the command before it checks it. - The command goes into the action log as typed. A password or token in the command is also in the action log, in Action History, and in the log file.
- The checks are a list of known patterns. They stop common high-damage mistakes. They do not stop every way to damage an endpoint, and they do not protect business data outside the protected paths.
- CrowdStrike's own tamper protection is the real defense for Falcon. The agent check in this package stops an operator mistake. It is not a guarantee.
- The Windows script always runs in 64-bit PowerShell. If the Tanium Client starts the 32-bit PowerShell, the script starts again in the 64-bit one.
- Windows: output on the error stream of a program is not counted. It goes to the action log as it is, without the 60-line limit.
- Linux: the Tanium client does not set
HOME. A command that reads$HOMEgets an empty value.~still points to the home folder of the client user,/root. - macOS runs the command in bash, not zsh. A command in zsh-only syntax behaves differently.
- The log file stays on the endpoint. Tanium removes the action folder after some time. The log file stays until a person or a cleanup deletes it. When the file passes 1 MB, the package keeps one old copy and starts a new file.
Test results
| What was tested | Expected | Result |
|---|---|---|
Windows, Audit, delete C:\Users |
BLOCKED, exit 0 |
Pass |
Windows, Run, delete C:\Users |
BLOCKED, exit 3 |
Pass |
| Windows, Run, delete a folder in a user profile | RAN, folder deleted, exit 0 |
Pass |
Windows, Run, Stop-Service on the Tanium Client |
BLOCKED, exit 5, endpoint stays online |
Pass |
Windows, Run, whoami |
nt authority\system |
Pass |
| Windows, no Mode selected | Counts as Audit, nothing ran | Pass |
Windows, special characters ` " & \| ^ % ! ' |
Command reaches the script unchanged | Pass |
| Windows, 200 output lines | 60 lines, TRUNCATED, whole log visible in the console |
Pass |
Linux, Audit and Run, delete /etc |
BLOCKED, exit 0 and exit 3 |
Pass |
Linux, Audit, delete /opt/Tanium |
BLOCKED as a security agent |
Pass |
| Linux, Run, delete with a path from a variable | BLOCKED, exit 3 |
Pass |
Linux, Run, systemctl stop taniumclient |
BLOCKED, exit 5 |
Pass |
| Linux, Run, decode-and-run | BLOCKED, exit 6 |
Pass |
Linux, shell characters $HOME, $(...), \ |
Reach the script unchanged | Pass |
| Linux, 200 output lines | 60 lines, TRUNCATED, all lines in the log file |
Pass |
| Linux, Run, a command that fails | FAILED, exit 1 |
Pass |
| Shutdown and power off blocked, restart allowed | BLOCKED, exit 3 |
Tested outside Tanium only |
| macOS | Same as Linux | Not tested |
| Endpoints with CrowdStrike or CyberArk installed | Agent commands blocked | Not tested |
Scripts
The page has two scripts. Select a tab to see each script.
<#
.SYNOPSIS
RunCommand.ps1
Break-glass package: checks one operator-supplied PowerShell command and,
in Run mode, runs it.
Built to run as a Tanium package (runs as SYSTEM). For Windows.
.DESCRIPTION
1. Reads Mode and the command, and URL-decodes the command.
2. Runs the safety checks. They stop the command when it deletes a
protected Windows path, runs a high-damage disk, boot, registry, or
shadow-copy operation, stops or removes CrowdStrike, Tanium, or CyberArk,
or uses an encoded command or Invoke-Expression.
3. Audit mode stops here and reports what Run mode would do.
Run mode runs the command in Windows PowerShell 5.1.
SECURITY MODEL: the real control is the content set and RBAC that limit
who can deploy this package. The checks prevent accidents. They are not a
security boundary, and a trusted operator who wants to get around them can.
Do not widen deploy rights because the checks exist.
.PARAMETER (positional, passed by Tanium as "$1" "$2")
$1 Mode Audit = run the checks and report, run nothing (default)
Run = run the checks, then run the command if they pass
$2 Command The PowerShell command to run. Required.
.NOTES
Tanium command line:
cmd.exe /d /c powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -NonInteractive -NoProfile -File RunCommand.ps1 "$1" "$2"
Exit codes:
0 Finished. Run: the command ran and returned 0. Audit: always 0
(read the BLOCKED or WOULD RUN line).
1 The command ran and failed: it returned a non-zero exit code or
stopped with an error. The log line gives the command's own code.
Some programs (robocopy) use non-zero codes for success.
2 A parameter was wrong (Mode, empty command, the value was split, or the
command is not valid PowerShell). Nothing ran.
3 Stopped by a check: protected Windows path, or a high-damage disk,
boot, registry, or shadow-copy operation. Nothing ran.
4 Unexpected error in the script. Nothing ran.
5 Stopped by a check: protected security agent. Nothing ran.
6 Stopped by a check: encoded command or Invoke-Expression. Nothing ran.
The first check that trips decides the code, except that a high-damage
operation (3) wins over a protected path found earlier.
Log:
The Tanium action log shows the important lines and the first 60 lines
of the command's output, because the console shows about 100 lines.
Every line, with up to 5000 output lines, goes to
C:\Windows\Temp\RunCommand.log. Change the two numbers below the header.
The command is logged as typed. A password or token in it is logged too.
Output that a program writes to its error stream is not captured. It
goes straight to the action log and is not counted or cut.
Works with Windows PowerShell 5.1.
#>
$ErrorActionPreference = 'Stop'
$ScriptVersion = '2.0.0'
$ScriptName = 'RunCommand'
$LogFile = Join-Path $env:windir ("Temp\{0}.log" -f $ScriptName)
$RawArgs = @($args)
# How many lines of the command's output to show in the Tanium action log, and
# to keep in the log file. Keep the first number well under 100.
$MaxActionLogOutputLines = 60
$MaxFileOutputLines = 5000
# If the Tanium Client started the 32-bit PowerShell on 64-bit Windows, start again in the
# 64-bit one. The raw (still URL-encoded) values are passed on, so they are decoded only once.
if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) {
$powershell64 = Join-Path $env:windir 'Sysnative\WindowsPowerShell\v1.0\powershell.exe'
if (Test-Path -LiteralPath $powershell64) {
# Windows PowerShell 5.1 drops an empty value when it starts a program, which would
# move the values after it one place to the left. '""' keeps the empty place.
$passOn = @($RawArgs | ForEach-Object { if ([string]::IsNullOrEmpty([string]$_)) { '""' } else { [string]$_ } })
& $powershell64 -ExecutionPolicy Bypass -NoProfile -NonInteractive -File $PSCommandPath @passOn
exit $LASTEXITCODE
}
}
# ----------------------------------------------------------------------------
# Logging: each line goes to the Tanium action log (Write-Host) and to the log
# file. -FileOnly keeps a detail line out of the action log.
# ----------------------------------------------------------------------------
function Write-Log {
param([string]$Message, [string]$Level = 'INFO', [switch]$FileOnly)
$line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
if (-not $FileOnly) { Write-Host $line }
try {
Add-Content -LiteralPath $LogFile -Value $line -Encoding UTF8
} catch {
# A logging problem must never stop the work.
}
}
function Start-LogFile {
# Keep the log from growing forever: once it passes 1 MB, keep one old copy.
try {
if (Test-Path -LiteralPath $LogFile) {
if ((Get-Item -LiteralPath $LogFile).Length -gt 1MB) {
Move-Item -LiteralPath $LogFile -Destination ($LogFile + '.old') -Force
}
}
} catch { }
}
function Get-PackageParameter {
# Tanium passes parameter values percent-encoded (for example %2C for a comma).
param([int]$Index, [string]$Default)
if ($RawArgs.Count -gt $Index -and $null -ne $RawArgs[$Index]) {
$value = [string]$RawArgs[$Index]
try { $value = [System.Uri]::UnescapeDataString($value) } catch { }
$value = $value.Trim().Trim('"').Trim("'").Trim()
if ($value -ne '') { return $value }
}
return $Default
}
function Complete-Run {
# Writes the summary and the last line, then stops the script with the exit code.
param([int]$Code, [string]$Summary)
if ($Summary) { Write-Log $Summary }
Write-Log ("===== Finished with exit code {0} =====" -f $Code)
exit $Code
}
$script:BlockCode = 0
$script:BlockText = $null
function Set-Block {
# Records the first reason to stop. Later reasons are ignored.
param([int]$Code, [string]$Text)
if (-not $script:BlockCode) { $script:BlockCode = $Code; $script:BlockText = $Text }
}
function Stop-IfBlocked {
# Call only as a statement at script level.
if (-not $script:BlockCode) { return }
if ($script:BlockCode -eq 2) {
Write-Log ('{0,-14}{1} Nothing ran.' -f 'WRONG INPUT', $script:BlockText) 'ERROR'
Complete-Run 2 ('Summary ({0}): wrong input, nothing ran' -f $Mode)
}
Write-Log ('{0,-14}{1}' -f 'BLOCKED', $script:BlockText) 'WARN'
if ($Mode -eq 'Audit') { Complete-Run 0 'Summary (Audit, nothing changed): would run=0; blocked=1' }
Complete-Run $script:BlockCode 'Summary (Run): blocked=1; nothing ran'
}
trap {
# Any unexpected error inside the checks: stop, run nothing, say why.
Write-Log ('Unexpected error in the safety checks, so nothing ran: {0}' -f $_.Exception.Message) 'ERROR'
Complete-Run 4 'Summary: unexpected error, nothing ran'
}
# ----------------------------------------------------------------------------
# Parameters
# ----------------------------------------------------------------------------
Start-LogFile
$Mode = Get-PackageParameter -Index 0 -Default 'Audit'
# The command is decoded only. Quotes and spaces at its ends are part of the command.
$RawCommand = ''
if ($RawArgs.Count -ge 2 -and $null -ne $RawArgs[1]) { $RawCommand = [string]$RawArgs[1] }
$DecodedCommand = $RawCommand
try { $DecodedCommand = [System.Uri]::UnescapeDataString($RawCommand) } catch { }
Write-Log ("===== {0} {1} started on {2} =====" -f $ScriptName, $ScriptVersion, $env:COMPUTERNAME)
# The command is logged as typed, so a secret in it is logged too.
Write-Log ("Settings: mode={0}; command={1}" -f $Mode, $DecodedCommand)
switch -Regex ($Mode) {
'^(?i)audit$' { $Mode = 'Audit' }
'^(?i)run$' { $Mode = 'Run' }
default {
Write-Log ('{0,-14}Mode must be Audit or Run. Got: {1}. Nothing ran.' -f 'WRONG INPUT', $Mode) 'ERROR'
Complete-Run 2 'Summary: wrong input, nothing ran'
}
}
if ($RawArgs.Count -gt 2) {
Write-Log ('{0,-14}the script received {1} values instead of 2. The command was split before it reached the script, so the quoting or URL-encoding broke. Nothing ran.' -f 'WRONG INPUT', $RawArgs.Count) 'ERROR'
Complete-Run 2 ('Summary ({0}): wrong input, nothing ran' -f $Mode)
}
if ([string]::IsNullOrWhiteSpace($DecodedCommand)) {
Write-Log ('{0,-14}the command is empty. Nothing ran.' -f 'WRONG INPUT') 'ERROR'
Complete-Run 2 ('Summary ({0}): wrong input, nothing ran' -f $Mode)
}
# ----- helpers --------------------------------------------------------
$script:Bases = @((Get-Location).ProviderPath) # folders a relative path could be resolved against
$script:CdDynamic = $false # a Set-Location target this script cannot read
$script:NeedWholeScan = $false # a delete this script cannot bind to one path
function Expand-EnvText {
# expands %var%, $env:var, ${env:var} and $pwd. An undefined $env: variable becomes
# empty text, the same as PowerShell does at run time ("$env:Nope\*" really is "\*").
param([string]$Text)
if (-not $Text) { return '' }
$t = [System.Environment]::ExpandEnvironmentVariables($Text)
$t = [regex]::Replace($t, '(?i)\$\{env:([^}]+)\}|\$env:([a-z_][a-z0-9_]*)', {
param($m)
$name = $m.Groups[2].Value
if ($m.Groups[1].Success) { $name = $m.Groups[1].Value }
$v = [System.Environment]::GetEnvironmentVariable($name)
if ($null -ne $v) { $v } else { '' }
})
$t = [regex]::Replace($t, '(?i)\$pwd\b', { param($m) (Get-Location).ProviderPath })
return $t
}
function Join-Segments {
# collapses . and .. and doubled separators, trims trailing dots and spaces the way
# Windows does, and expands 8.3 short names (PROGRA~1) when the folder exists
param([string]$Drive, [string]$Rest, [bool]$IsFileSystem)
$out = New-Object System.Collections.ArrayList
foreach ($s in ($Rest -split '\\')) {
if ($s -eq '' -or $s -eq '.') { continue }
if ($s -eq '..') { if ($out.Count -gt 0) { $out.RemoveAt($out.Count - 1) }; continue }
$seg = $s.TrimEnd('.', ' ')
if ($seg -eq '') { continue }
if ($IsFileSystem -and $seg -match '~\d' -and $seg -notmatch '[*?\[]') {
try {
$parent = $Drive + '\' + (($out.ToArray()) -join '\')
if (-not $parent.EndsWith('\')) { $parent += '\' }
$found = @([System.IO.Directory]::GetFileSystemEntries($parent, $seg))
if ($found.Count -ge 1) { $seg = [System.IO.Path]::GetFileName($found[0]) }
} catch { }
}
[void]$out.Add($seg)
}
return ($Drive + '\' + (($out.ToArray()) -join '\'))
}
function ConvertTo-CheckPath {
# Turns a path as typed into the normalized absolute form(s) the lists are matched against,
# for example 'C:\Windows\System32', 'HKLM:\SOFTWARE\X' or '\\host\share\x'.
# A relative path gives one result per folder in $script:Bases.
param([string]$Text, [switch]$RegistryContext)
$t = (Expand-EnvText $Text).Trim().Trim('"', "'").Trim()
if (-not $t) { return @() }
$t = $t -replace '/', '\'
$t = $t -replace '(?i)^(Microsoft\.PowerShell\.Core\\)?FileSystem::', ''
# registry: HKLM:\x, HKLM:x, Registry::HKEY_LOCAL_MACHINE\x, and for reg.exe HKLM\x or \\host\HKLM\x
$hiveRx = '(?i)^(?<prov>(?:Microsoft\.PowerShell\.Core\\)?Registry::)?(?:\\\\[^\\]+\\)?(?<hive>HKLM|HKEY_LOCAL_MACHINE|HKCU|HKEY_CURRENT_USER|HKCR|HKEY_CLASSES_ROOT|HKU|HKEY_USERS|HKCC|HKEY_CURRENT_CONFIG)(?<sep>:\\?|\\|$)(?<rest>.*)$'
if ($t -match $hiveRx) {
$isReg = $RegistryContext -or $Matches['prov'] -or $Matches['sep'].StartsWith(':')
if ($isReg) {
$rest = $Matches['rest']
switch -Regex ($Matches['hive']) {
'(?i)^(HKLM|HKEY_LOCAL_MACHINE)$' { return @(Join-Segments 'HKLM:' $rest $false) }
'(?i)^(HKCR|HKEY_CLASSES_ROOT)$' { return @(Join-Segments 'HKLM:' ('SOFTWARE\Classes\' + $rest) $false) }
'(?i)^(HKU|HKEY_USERS)$' { return @(Join-Segments 'HKU:' $rest $false) }
'(?i)^(HKCU|HKEY_CURRENT_USER)$' { return @(Join-Segments 'HKCU:' $rest $false) }
default { return @(Join-Segments 'HKCC:' $rest $false) }
}
}
}
# \\?\C:\x and \\.\C:\x and \\?\UNC\host\share
$t = $t -replace '(?i)^\\\\[?.]\\UNC\\', '\\'
$t = $t -replace '^\\\\[?.]\\', ''
# the local admin shares are just the local drive
$me = [regex]::Escape([string]$env:COMPUTERNAME)
$local = "(?:localhost|127\.0\.0\.1|\.|$me)"
if ($t -match "(?i)^\\\\$local\\([a-z])\`$(\\.*)?`$") { $t = $Matches[1] + ':' + [string]$Matches[2] }
elseif ($t -match "(?i)^\\\\$local\\admin\`$(\\.*)?`$") { $t = [string]$env:windir + [string]$Matches[1] }
# UNC
if ($t -match '^\\\\([^\\]+)\\([^\\]+)(.*)$') {
return @(Join-Segments ('\\' + $Matches[1] + '\' + $Matches[2]) $Matches[3] $false)
}
# drive letter (C:\x, and C:x which is treated as C:\x)
if ($t -match '^([A-Za-z]):(.*)$') {
return @(Join-Segments ($Matches[1].ToUpper() + ':') $Matches[2] $true)
}
# another PowerShell drive (Env:, Cert:, Function:, Variable:) is not checked
if ($t -match '^[A-Za-z][\w.]*:') { return @() }
# relative, or rooted without a drive (\Windows): resolve against every known folder
$results = New-Object System.Collections.ArrayList
foreach ($b in $script:Bases) {
if (-not $b) { continue }
$full = $null
if ($t.StartsWith('\')) {
if ($b -match '^([A-Za-z]:|HK[A-Z]+:)') { $full = $Matches[1] + $t }
elseif ($b -match '^(\\\\[^\\]+\\[^\\]+)') { $full = $Matches[1] + $t }
}
else { $full = $b.TrimEnd('\') + '\' + $t }
if ($full) {
foreach ($n in (ConvertTo-CheckPath -Text $full -RegistryContext:$false)) {
if ($results -notcontains $n) { [void]$results.Add($n) }
}
}
}
return @($results.ToArray())
}
# ----- protected locations --------------------------------------------
# Class: fs (any drive letter) or a registry hive. Mode:
# Allow - cleanup folders that may be deleted even though they sit under a protected folder
# Subtree - the folder and everything in it
# Exact - the folder itself (and "folder\*"), but not single items inside it
# A path is also protected when it is a PARENT of a protected folder (C:\ProgramData holds
# C:\ProgramData\Microsoft\Windows), and when a wildcard in it could match one (C:\Win*).
$script:Roots = New-Object System.Collections.ArrayList
function Add-Root {
param([string]$Class, [string]$Path, [string]$Mode, [string]$Kind)
[void]$script:Roots.Add([pscustomobject]@{
Class = $Class; Segs = @($Path -split '\\' | Where-Object { $_ }); Mode = $Mode; Kind = $Kind
})
}
foreach ($p in 'Windows\Temp', 'Windows\SoftwareDistribution\Download', 'Windows\ccmcache', 'Windows\Logs') { Add-Root 'fs' $p 'Allow' '' }
foreach ($p in 'Windows', 'Boot', 'Recovery', 'System Volume Information', 'Program Files\WindowsApps',
'Program Files (x86)\WindowsApps', 'ProgramData\Microsoft\Windows', '$Recycle.Bin') { Add-Root 'fs' $p 'Subtree' 'os' }
# 'Users' is new in v2 (C:\Users and C:\Users\* only). Remove it if you do not want it.
foreach ($p in 'Program Files', 'Program Files (x86)', 'Users') { Add-Root 'fs' $p 'Exact' 'os' }
# security agent folders and registry keys. Add your real install folders if they differ.
$AgentFolderNames = 'CrowdStrike', 'Tanium', 'CyberArk'
foreach ($parent in 'Program Files', 'Program Files (x86)', 'ProgramData') {
foreach ($v in $AgentFolderNames) { Add-Root 'fs' "$parent\$v" 'Subtree' 'agent' }
}
foreach ($p in 'SYSTEM', 'SAM', 'SECURITY') { Add-Root 'HKLM' $p 'Subtree' 'os' }
foreach ($p in 'SOFTWARE', 'SOFTWARE\Microsoft', 'SOFTWARE\Microsoft\Windows', 'SOFTWARE\Microsoft\Windows\CurrentVersion',
'SOFTWARE\Microsoft\Windows NT', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'SOFTWARE\Classes',
'SOFTWARE\Policies', 'SOFTWARE\WOW6432Node') { Add-Root 'HKLM' $p 'Exact' 'os' }
foreach ($v in $AgentFolderNames) {
Add-Root 'HKLM' "SOFTWARE\$v" 'Subtree' 'agent'
Add-Root 'HKLM' "SOFTWARE\WOW6432Node\$v" 'Subtree' 'agent'
}
Add-Root 'HKU' '' 'Exact' 'os'
# When Tanium runs this, the script sits in <Tanium Client>\Downloads\Action_<id>. Protect the
# client folder wherever it is installed, but let the operator clean this action's own folder.
if ($PSScriptRoot -match '^[A-Za-z]:\\(.+)\\Downloads\\Action_\d+$') {
Add-Root 'fs' $Matches[1] 'Subtree' 'agent'
Add-Root 'fs' $PSScriptRoot.Substring(3) 'Allow' ''
}
function Test-Seg {
# does one typed path segment (maybe with wildcards) match one protected segment
param([string]$Typed, [string]$Root)
if ($Typed -match '[*?\[]') {
try { return ($Root -like $Typed) } catch { return ($Typed -eq $Root) }
}
return ($Typed -eq $Root)
}
function Get-ProtectionKind {
# returns $null, 'os' or 'agent' for one normalized path
param([string]$NormPath)
$class = $null; $rest = ''
if ($NormPath -match '^(\\\\[^\\]+\\[^\\]+)') {
# admin shares on other hosts stay blocked as a whole, as in v1
if ($Matches[1] -match '(?i)\\([a-z]|admin)\$$') { return 'os' }
return $null
}
elseif ($NormPath -match '^[A-Za-z]:(.*)$') { $class = 'fs'; $rest = $Matches[1] }
elseif ($NormPath -match '^(HK[A-Z]+):(.*)$') { $class = $Matches[1].ToUpper(); $rest = $Matches[2] }
else { return $null }
$segs = @($rest -split '\\' | Where-Object { $_ })
foreach ($r in $script:Roots) {
if ($r.Mode -ne 'Allow' -or $r.Class -ne $class -or $segs.Count -lt $r.Segs.Count) { continue }
$same = $true
for ($i = 0; $i -lt $r.Segs.Count; $i++) { if ($segs[$i] -ne $r.Segs[$i]) { $same = $false; break } }
if ($same) { return $null } # allow wins
}
$kind = $null
foreach ($r in $script:Roots) {
if ($r.Mode -eq 'Allow' -or $r.Class -ne $class) { continue }
$n = [Math]::Min($segs.Count, $r.Segs.Count)
$overlap = $true
for ($i = 0; $i -lt $n; $i++) { if (-not (Test-Seg $segs[$i] $r.Segs[$i])) { $overlap = $false; break } }
if (-not $overlap) { continue }
$hit = $false
if ($segs.Count -le $r.Segs.Count) { $hit = $true } # the root itself, or a parent of it
elseif ($r.Mode -eq 'Subtree') { $hit = $true } # something inside it
elseif ($segs.Count -eq ($r.Segs.Count + 1) -and ($segs[$segs.Count - 1] -eq '*' -or $segs[$segs.Count - 1] -eq '*.*')) { $hit = $true }
if ($hit) {
if ($r.Kind -eq 'os') { return 'os' }
$kind = 'agent'
}
}
return $kind
}
function Test-Protected {
# returns $null, or an object with Kind ('os' / 'agent') and the normalized Path that matched
param([string]$Token, [switch]$RegistryContext)
foreach ($n in (ConvertTo-CheckPath -Text $Token -RegistryContext:$RegistryContext)) {
$k = Get-ProtectionKind $n
if ($k) { return [pscustomobject]@{ Kind = $k; Path = $n } }
}
return $null
}
function Set-PathBlock {
param($Hit, [string]$Typed, [string]$How = 'deletes')
$shown = "'$($Hit.Path)'"
if ($Typed -and $Typed.Trim('"', "'") -ne $Hit.Path) { $shown = "'$Typed' (checked as '$($Hit.Path)')" }
if ($Hit.Kind -eq 'agent') {
Set-Block 5 "command $How $shown, which belongs to a protected security agent (CrowdStrike, Tanium, or CyberArk)."
}
else {
Set-Block 3 "command $How $shown, a protected OS path."
}
}
function Test-IsRelative {
param([string]$Text)
$t = (Expand-EnvText $Text).Trim().Trim('"', "'") -replace '/', '\'
return ($t -notmatch '^(\\\\|[A-Za-z][\w.]*:|(Microsoft\.PowerShell\.Core\\)?\w+::)')
}
function Find-ProtectedToken {
# Conservative fallback for deletes this script cannot bind to one path: test every
# path-looking token in the text.
param([string]$Text)
$rx = '(?i)(?<![\w:\\])(?:[a-z]:[\\/]|%[\w()]+%|\$env:\w+|\$\{env:[^}]+\}|\\\\[^\\\s"'']+\\)[^"''|;&<>\r\n]*'
foreach ($m in [regex]::Matches($Text, $rx)) {
$whole = $m.Value.Trim()
# the whole token, then the token cut at the first space, ")" or ","
foreach ($cand in @($whole, ($whole -split '\s+')[0], ($whole -split '\)')[0], ($whole -split ',')[0]) | Select-Object -Unique) {
$hit = Test-Protected $cand
if ($hit) { return [pscustomobject]@{ Hit = $hit; Typed = $cand } }
}
}
foreach ($m in [regex]::Matches($Text, '(?<![\w:\\.%$])\\[A-Za-z$][^\s"''|;&<>]*')) { # \Windows
$hit = Test-Protected $m.Value
if ($hit) { return [pscustomobject]@{ Hit = $hit; Typed = $m.Value } }
}
return $null
}
function Test-KnownVariable {
param($Node)
return ($Node -is [System.Management.Automation.Language.VariableExpressionAst] -and
($Node.VariablePath.DriveName -eq 'env' -or $Node.VariablePath.UserPath -eq 'pwd'))
}
function Get-Literal {
# Reads the literal text of one argument. Dynamic is $true when any part of it is only
# known at run time (a variable, a sub-expression, a method call).
param($Node)
$r = [pscustomobject]@{ Dynamic = $false; Values = @() }
if ($null -eq $Node) { return $r }
if ($Node -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $r.Values = @([string]$Node.Value); return $r }
if ($Node -is [System.Management.Automation.Language.ConstantExpressionAst]) { $r.Values = @([string]$Node.Value); return $r }
if ($Node -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) {
foreach ($n in $Node.NestedExpressions) { if (-not (Test-KnownVariable $n)) { $r.Dynamic = $true; return $r } }
$r.Values = @(Expand-EnvText $Node.Value); return $r
}
if ($Node -is [System.Management.Automation.Language.VariableExpressionAst]) {
if (-not $Node.Splatted -and (Test-KnownVariable $Node)) { $r.Values = @(Expand-EnvText $Node.Extent.Text); return $r }
$r.Dynamic = $true; return $r
}
if ($Node -is [System.Management.Automation.Language.ArrayLiteralAst]) {
foreach ($e in $Node.Elements) {
$x = Get-Literal $e
if ($x.Dynamic) { $r.Dynamic = $true; return $r }
$r.Values = @($r.Values) + @($x.Values)
}
return $r
}
if ($Node -is [System.Management.Automation.Language.ParenExpressionAst]) {
$pl = $Node.Pipeline
if ($pl -is [System.Management.Automation.Language.PipelineAst] -and $pl.PipelineElements.Count -eq 1 -and
$pl.PipelineElements[0] -is [System.Management.Automation.Language.CommandExpressionAst]) {
return (Get-Literal $pl.PipelineElements[0].Expression)
}
}
$r.Dynamic = $true; return $r
}
function Get-BoundArgs {
# Small static parameter binder. Returns a hashtable: parameter name -> list of argument ASTs,
# '_pos' -> positional arguments in order. A switch is present as a key with an empty list.
# An unknown or ambiguous parameter name is treated as a switch, so the argument after it is
# checked as a positional value (the safe direction).
param($Cmd, [string[]]$ValueParams, [string[]]$SwitchParams, [hashtable]$Aliases)
$valueAll = @($ValueParams) + @('ErrorAction', 'WarningAction', 'InformationAction', 'ErrorVariable', 'WarningVariable',
'InformationVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable')
$switchAll = @($SwitchParams) + @('Verbose', 'Debug', 'WhatIf', 'Confirm')
$aliasAll = @{ ea = 'ErrorAction'; wa = 'WarningAction'; infa = 'InformationAction'; ev = 'ErrorVariable'; wv = 'WarningVariable'
iv = 'InformationVariable'; ov = 'OutVariable'; ob = 'OutBuffer'; pv = 'PipelineVariable'; vb = 'Verbose'
db = 'Debug'; wi = 'WhatIf'; cf = 'Confirm' }
if ($Aliases) { foreach ($k in $Aliases.Keys) { $aliasAll[$k] = $Aliases[$k] } }
$result = @{ _pos = (New-Object System.Collections.ArrayList) }
$pending = $null
for ($i = 1; $i -lt $Cmd.CommandElements.Count; $i++) {
$el = $Cmd.CommandElements[$i]
if ($el -is [System.Management.Automation.Language.CommandParameterAst]) {
$pending = $null
$typed = [string]$el.ParameterName
$name = $typed
if ($aliasAll.ContainsKey($typed)) { $name = $aliasAll[$typed] }
else {
$exact = @(@($valueAll) + @($switchAll) | Where-Object { $_ -eq $typed })
if ($exact.Count -ge 1) { $name = $exact[0] }
else {
$prefix = @(@($valueAll) + @($switchAll) | Where-Object { $_ -like "$typed*" })
if ($prefix.Count -eq 1) { $name = $prefix[0] }
}
}
if (-not $result.ContainsKey($name)) { $result[$name] = (New-Object System.Collections.ArrayList) }
if ($el.Argument) { [void]$result[$name].Add($el.Argument) } # -Name:value
elseif ($valueAll -contains $name) { $pending = $name }
continue
}
if ($pending) { [void]$result[$pending].Add($el); $pending = $null }
else { [void]$result['_pos'].Add($el) }
}
return $result
}
$script:CmdCache = @{}
function Get-CmdInfo {
# Follows an alias to its real command (rm -> Remove-Item, kill -> Stop-Process).
# It reads the alias Definition. ResolvedCommand is empty until the module that owns the
# target cmdlet has been loaded, which it has not in a new Windows PowerShell started by a package.
param([string]$Name)
if (-not $Name) { return [pscustomobject]@{ Name = ''; Leaf = ''; Type = 'Unknown' } }
if ($script:CmdCache.ContainsKey($Name)) { return $script:CmdCache[$Name] }
$n = $Name.Trim('"', "'"); $type = 'Unknown'
if ($n -notmatch '[*?\[\]$`]' -and $n.Length -lt 260) {
for ($hop = 0; $hop -lt 5; $hop++) {
$c = $null
try { $c = @(Get-Command -Name $n -ErrorAction SilentlyContinue)[0] } catch { $c = $null }
if (-not $c) { break }
if ($c.CommandType -eq 'Alias') { $n = [string]$c.Definition; continue }
$n = [string]$c.Name; $type = [string]$c.CommandType; break
}
}
$leaf = ($n -replace '^.*[\\/]', '') -replace '(?i)\.(exe|com|cmd|bat)$', ''
$info = [pscustomobject]@{ Name = $n; Leaf = $leaf; Type = $type }
$script:CmdCache[$Name] = $info
return $info
}
function Get-AstCmdInfo {
param($Cmd)
$nm = $Cmd.GetCommandName()
if (-not $nm) { $nm = [string]$Cmd.CommandElements[0].Extent.Text } # & "$env:windir\System32\cmd.exe"
return (Get-CmdInfo $nm)
}
function Get-PipelineSource {
# for a command fed by the pipeline (also inside ForEach-Object { }), returns the first
# element of that pipeline
param($Cmd)
$node = $Cmd
while ($node) {
$parent = $node.Parent
if ($parent -is [System.Management.Automation.Language.PipelineAst] -and $parent.PipelineElements.Count -gt 1 -and
$parent.PipelineElements[0] -ne $node) {
return $parent.PipelineElements[0]
}
$node = $parent
}
return $null
}
# ----- 1. Parse -------------------------------------------------------
$tok = $null; $perr = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($DecodedCommand, [ref]$tok, [ref]$perr)
if ($perr -and $perr.Count -gt 0) {
Set-Block 2 "input did not parse cleanly as PowerShell ($($perr[0].Message))."
}
Stop-IfBlocked
# Command lines hidden inside the command (cmd /c "...", powershell -Command "...",
# Start-Process -ArgumentList ...) are parsed too, so the checks below see them.
$script:Cmds = New-Object System.Collections.ArrayList # every command found: Cmd, Info, Nested
$script:AllAsts = New-Object System.Collections.ArrayList
$script:SeenText = @{}
$NestedDeleteVerb = '(?i)(?<![\w\\.:$-])(del|erase|rd|rmdir|rm|ri|Remove-Item)(?![\w\\.:-])'
$Launchers = 'cmd', 'powershell', 'pwsh', 'psexec', 'psexec64', 'wmic', 'schtasks', 'forfiles', 'start'
function Add-Ast {
param($Tree, [bool]$Nested, [int]$Depth)
[void]$script:AllAsts.Add($Tree)
$found = $Tree.FindAll({ param($n) $n -is [System.Management.Automation.Language.CommandAst] }, $true)
foreach ($c in $found) {
$info = Get-AstCmdInfo $c
[void]$script:Cmds.Add([pscustomobject]@{ Cmd = $c; Info = $info; Nested = $Nested })
# does this command carry another command line in its arguments?
$carrier = ($info.Name -eq 'Start-Process') -or ($Launchers -contains $info.Leaf)
if (-not $carrier -and -not $Nested -and $info.Type -in 'Application', 'ExternalScript', 'Unknown') { $carrier = $true }
if ($carrier -and $c.CommandElements.Count -gt 1) {
$vals = New-Object System.Collections.ArrayList
for ($i = 1; $i -lt $c.CommandElements.Count; $i++) {
$el = $c.CommandElements[$i]
$strings = @($el.FindAll({ param($n) $n -is [System.Management.Automation.Language.StringConstantExpressionAst] -or
$n -is [System.Management.Automation.Language.ExpandableStringExpressionAst] }, $true))
if ($el -is [System.Management.Automation.Language.StringConstantExpressionAst] -or
$el -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) { $strings = @($el) }
if ($strings.Count -eq 0) { [void]$vals.Add([string]$el.Extent.Text); continue }
foreach ($s in $strings) {
$v = [string]$s.Value
if ($v -match '\s') {
if ($v -match '\$') { $v = '"' + ($v -replace '"', '`"') + '"' } else { $v = "'" + ($v -replace "'", "''") + "'" }
}
[void]$vals.Add($v)
}
}
$arr = $vals.ToArray()
for ($i = 0; $i -lt $arr.Count; $i++) { Add-CommandText (($arr[$i..($arr.Count - 1)]) -join ' ') ($Depth + 1) }
}
}
# any quoted string that looks like a command line
$quoted = $Tree.FindAll({ param($n)
($n -is [System.Management.Automation.Language.StringConstantExpressionAst] -or
$n -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) -and
$n.StringConstantType -ne 'BareWord' -and ([string]$n.Value) -match '\S\s+\S' }, $true)
foreach ($s in $quoted) { Add-CommandText ([string]$s.Value) ($Depth + 1) }
}
function Add-CommandText {
param([string]$Text, [int]$Depth)
if (-not $Text -or $Depth -gt 12) { return } # each unwrap makes the text shorter; 12 is a safety stop
$key = $Text.Trim()
if (-not $key -or $script:SeenText.ContainsKey($key)) { return }
$script:SeenText[$key] = $true
# "/c rd /s /q C:\x" or "-NoProfile -Command Remove-Item C:\x": also read it without the leading switches
$bare = $key -replace '^(?:[/-]\S+\s+)+', ''
if ($bare -ne $key) { Add-CommandText $bare ($Depth + 1) }
$tk = $null; $er = $null
$tree = [System.Management.Automation.Language.Parser]::ParseInput($key, [ref]$tk, [ref]$er)
if ($er -and $er.Count -gt 0) {
# cmd.exe syntax that PowerShell cannot parse: try the pieces between & && | ||
$parts = @($key -split '\s*(?:&&|\|\||&|\|)\s*' | Where-Object { $_ })
if ($parts.Count -gt 1) { foreach ($p in $parts) { Add-CommandText $p ($Depth + 1) } }
elseif ($key -match $NestedDeleteVerb) { $script:NeedWholeScan = $true }
return
}
Add-Ast $tree $true $Depth
}
$script:SeenText[$DecodedCommand.Trim()] = $true
Add-Ast $ast $false 0
# folders a relative path could mean: the current folder plus every literal Set-Location target
foreach ($rec in $script:Cmds) {
if ($rec.Info.Name -notin 'Set-Location', 'Push-Location') { continue }
for ($i = 1; $i -lt $rec.Cmd.CommandElements.Count; $i++) {
$el = $rec.Cmd.CommandElements[$i]
if ($el -is [System.Management.Automation.Language.CommandParameterAst]) {
if ($el.Argument) { $el = $el.Argument } else { continue }
}
$lit = Get-Literal $el
if ($lit.Dynamic) { $script:CdDynamic = $true; continue }
foreach ($v in $lit.Values) {
if ($v -match '^/[A-Za-z]$' -or $v -eq '-' -or $v -eq '+') { continue } # cd /d
foreach ($n in (ConvertTo-CheckPath -Text $v)) { if ($script:Bases -notcontains $n) { $script:Bases += $n } }
}
}
}
# ----- 2. Hard blocks (obfuscation / nested eval) --------------------
# -EncodedCommand in any accepted spelling (-e, -ec, -en, -enc ... and /enc), quoted or not
if ($DecodedCommand -match '(?i)\b(powershell|pwsh)(\.exe)?\b[^;|&\r\n]*?(?<![\w-])[-/]e(c|n|nc|nco|ncod|ncode|ncoded|ncodedc[a-z]*)?[\s,"'']+[A-Za-z0-9+/=]{8,}') {
Set-Block 6 'encoded command (-EncodedCommand) is not allowed.'
}
foreach ($rec in $script:Cmds) {
if ($rec.Info.Name -eq 'Invoke-Expression') { Set-Block 6 'nested Invoke-Expression is not allowed.' }
}
Stop-IfBlocked
# ----- 3. Delete protection ------------------------------------------
$RemoveItemValue = 'Path', 'LiteralPath', 'Filter', 'Include', 'Exclude', 'Credential', 'Stream'
$RemoveItemSwitch = 'Recurse', 'Force', 'UseTransaction'
$GetChildValue = 'Path', 'LiteralPath', 'Filter', 'Include', 'Exclude', 'Depth', 'Attributes', 'Credential', 'Stream'
$GetChildSwitch = 'Recurse', 'Force', 'Name', 'Directory', 'File', 'Hidden', 'ReadOnly', 'System', 'FollowSymlink', 'UseTransaction'
$PathAliases = @{ PSPath = 'LiteralPath'; LP = 'LiteralPath'; s = 'Recurse'; ad = 'Directory'; af = 'File'; h = 'Hidden'; ar = 'ReadOnly'; as = 'System' }
function Get-SourcePatterns {
# For "Get-ChildItem <path> | Remove-Item": returns the path patterns the delete can reach,
# or $null when the source is not a Get-ChildItem / Get-Item / literal list this script can read.
param($Source)
if ($Source -is [System.Management.Automation.Language.CommandExpressionAst]) {
$lit = Get-Literal $Source.Expression
if ($lit.Dynamic -or @($lit.Values).Count -eq 0) { return $null }
return @($lit.Values)
}
if ($Source -isnot [System.Management.Automation.Language.CommandAst]) { return $null }
$name = (Get-AstCmdInfo $Source).Name
if ($name -notin 'Get-ChildItem', 'Get-Item') { return $null }
$b = Get-BoundArgs $Source $GetChildValue $GetChildSwitch $PathAliases
$pathAsts = @($b['Path']) + @($b['LiteralPath']) | Where-Object { $_ }
$pos = @($b['_pos'].ToArray())
$filterAsts = @($b['Filter']) | Where-Object { $_ }
if ($pos.Count -ge 1 -and @($pathAsts).Count -eq 0) { $pathAsts = @($pos[0]); if ($pos.Count -ge 2) { $filterAsts = @($filterAsts) + @($pos[1]) } }
elseif ($pos.Count -ge 1) { $filterAsts = @($filterAsts) + @($pos[0]) }
$paths = @()
foreach ($a in $pathAsts) { $lit = Get-Literal $a; if ($lit.Dynamic) { return $null }; $paths += @($lit.Values) }
if ($paths.Count -eq 0) { $paths = @('.') }
if ($name -eq 'Get-Item') { return $paths }
$leaf = '*'
if (@($filterAsts).Count -ge 1) { $lit = Get-Literal $filterAsts[0]; if (-not $lit.Dynamic -and @($lit.Values).Count -eq 1 -and $lit.Values[0]) { $leaf = $lit.Values[0] } }
$recurse = $b.ContainsKey('Recurse') -or $b.ContainsKey('Depth')
$out = @()
foreach ($p in $paths) {
$root = $p.TrimEnd('\', '/')
if ($root -match '^[A-Za-z]:$' -or $root -eq '') { $root = $p.TrimEnd('\', '/') }
$out += ($root + '\' + $leaf)
if ($recurse) { $out += ($root + '\*\' + $leaf) }
if (($p -split '[\\/]')[-1] -match '[*?\[]') { $out += $p }
}
return $out
}
# 3a. PowerShell-native deletes - read path args straight from the AST
foreach ($rec in $script:Cmds) {
if ($rec.Info.Name -ne 'Remove-Item') { continue }
$c = $rec.Cmd
$b = Get-BoundArgs $c $RemoveItemValue $RemoveItemSwitch $PathAliases
$pathAsts = @(@($b['Path']) + @($b['LiteralPath']) + @($b['_pos'].ToArray()) | Where-Object { $_ })
$dynamic = $false; $pipeVarOnly = $true
foreach ($a in $pathAsts) {
$lit = Get-Literal $a
if ($lit.Dynamic) {
$dynamic = $true
$vars = @($a.FindAll({ param($n) $n -is [System.Management.Automation.Language.VariableExpressionAst] }, $true))
if ($vars.Count -eq 0) { $pipeVarOnly = $false }
foreach ($v in $vars) { if ($v.VariablePath.UserPath -notin '_', 'PSItem') { $pipeVarOnly = $false } }
continue
}
foreach ($t in $lit.Values) {
if (-not $t) { continue }
if ($script:CdDynamic -and (Test-IsRelative $t)) {
Set-Block 3 "command deletes the relative path '$t' after a Set-Location whose target this script cannot read."
}
$hit = Test-Protected $t
if ($hit) { Set-PathBlock $hit $t }
}
}
if ($dynamic -or $pathAsts.Count -eq 0) {
$patterns = $null
if ($pathAsts.Count -eq 0 -or $pipeVarOnly) {
$src = Get-PipelineSource $c
if ($src) { $patterns = Get-SourcePatterns $src }
}
if ($patterns) {
foreach ($t in $patterns) {
if ($script:CdDynamic -and (Test-IsRelative $t)) {
Set-Block 3 "command deletes items piped from the relative path '$t' after a Set-Location whose target this script cannot read."
}
$hit = Test-Protected $t
if ($hit) { Set-PathBlock $hit $t 'deletes items piped from' }
}
}
elseif ($rec.Nested) { $script:NeedWholeScan = $true }
else {
Set-Block 3 'Remove-Item with no literal path this script can check (path built from a variable, or piped from something other than Get-ChildItem or Get-Item with a literal path).'
}
}
}
# 3b. .NET IO deletes - [IO.File]::Delete(...) / [IO.Directory]::Delete(...)
foreach ($tree in $script:AllAsts) {
$deletes = $tree.FindAll({
param($n)
$n -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and
([string]$n.Member.Extent.Text).Trim('"', "'") -match '(?i)^Delete$'
}, $true)
foreach ($d in $deletes) {
if ($d.Expression.ToString() -match '(?i)IO\.(File|Directory)') {
$lit = @()
foreach ($a in @($d.Arguments)) {
$x = Get-Literal $a
if (-not $x.Dynamic) { $lit += @($x.Values | Where-Object { $_ -and $_ -notmatch '^(True|False)$' }) }
}
if ($lit.Count -eq 0) { Set-Block 3 '.NET IO delete with no literal path to check.' }
foreach ($t in $lit) { $hit = Test-Protected $t; if ($hit) { Set-PathBlock $hit $t } }
}
else { $script:NeedWholeScan = $true } # (Get-Item C:\x).Delete()
}
}
# 3c. deletes this script cannot bind to one path (inside cmd /c, forfiles, an unparsed string):
# test every path token in the whole command
if ($script:NeedWholeScan) {
$found = Find-ProtectedToken $DecodedCommand
if ($found) { Set-PathBlock $found.Hit $found.Typed 'contains a delete and names' }
}
# 3d. registry deletes (reg.exe) and mirror copies (robocopy /MIR deletes in the destination)
foreach ($rec in $script:Cmds) {
$c = $rec.Cmd
if ($rec.Info.Leaf -eq 'reg' -and $c.CommandElements.Count -ge 3) {
$verb = Get-Literal $c.CommandElements[1]
if (-not $verb.Dynamic -and $verb.Values[0] -eq 'delete') {
$key = Get-Literal $c.CommandElements[2]
if ($key.Dynamic) {
if (-not $rec.Nested) { Set-Block 3 'reg delete with a key name this script cannot read (built from a variable).' }
}
else {
$hit = Test-Protected $key.Values[0] -RegistryContext
if ($hit) { Set-PathBlock $hit $key.Values[0] }
}
}
}
if ($rec.Info.Leaf -eq 'robocopy') {
$plain = @(); $switches = @()
for ($i = 1; $i -lt $c.CommandElements.Count; $i++) {
$x = Get-Literal $c.CommandElements[$i]
if ($x.Dynamic) { $plain += $null; continue } # keeps its position; checked below
foreach ($v in $x.Values) { if ($v -match '^/') { $switches += $v } else { $plain += $v } }
}
$mirror = @($switches | Where-Object { $_ -match '(?i)^/(MIR|PURGE)$' }).Count -gt 0
$move = @($switches | Where-Object { $_ -match '(?i)^/(MOVE|MOV)$' }).Count -gt 0
$targets = @()
if ($mirror -and $plain.Count -ge 2) { $targets += , @($plain[1], 'mirrors into (and deletes extra files in)') }
if ($move -and $plain.Count -ge 1) { $targets += , @($plain[0], 'moves files out of') }
foreach ($t in $targets) {
if ($null -eq $t[0]) {
if (-not $rec.Nested) { Set-Block 3 'robocopy /MIR, /PURGE or /MOVE with a folder this script cannot read (built from a variable).' }
continue
}
$hit = Test-Protected $t[0]
if ($hit) { Set-PathBlock $hit $t[0] $t[1] }
}
}
}
# 3e. high-damage system operations - blocked outright
$NativeHardBlocks = @(
'(?i)\bformat(\.com)?\s+["'']?[a-z]:',
'(?i)\bvssadmin(\.exe)?\s+delete\s+shadows',
'(?i)\bwbadmin(\.exe)?\s+delete',
'(?i)\bbcdedit(\.exe)?\b.*/(delete|deletevalue)',
'(?i)\bcipher(\.exe)?\s+/w',
'(?i)\bdiskpart\b',
'(?i)\breg(\.exe)?["'']?\s+delete\s+["'']?(\\\\[^\\\s]+\\)?(HKLM|HKEY_LOCAL_MACHINE)\\(SYSTEM|SAM|SECURITY)\b',
'(?i)\bwmic(\.exe)?\b.*\bshadowcopy\b.*\bdelete\b',
'(?i)Win32_ShadowCopy.*(Remove-|Delete)|(Remove-|Delete).*Win32_ShadowCopy'
)
$hard = $false
foreach ($h in $NativeHardBlocks) { if ($DecodedCommand -match $h) { $hard = $true } }
foreach ($rec in $script:Cmds) {
if ($rec.Info.Name -in 'Format-Volume', 'Clear-Disk', 'Remove-Partition', 'Initialize-Disk') { $hard = $true }
}
if ($hard -and $script:BlockCode -ne 5) {
# keep the v1 order: a hard block is reported before a protected path
$script:BlockCode = 3
$script:BlockText = 'command matches a high-damage system operation (disk/boot/registry/shadow-copy).'
}
Stop-IfBlocked
# 3f. power off. A powered-off endpoint cannot be started again from Tanium. A restart is allowed.
# shutdown /s, /sg, /p, /h (and -s ...), Stop-Computer, and Win32Shutdown / wmic ... shutdown.
$powerOff = $DecodedCommand -match '(?i)\bshutdown(\.exe)?["'']?\s+([^;|&\r\n]*\s)?[/-](s|sg|p|h)\b'
if ($DecodedCommand -match '(?i)\.Win32Shutdown\s*\(|\bwmic(\.exe)?\b.*\bcall\s+(shutdown|win32shutdown)\b') { $powerOff = $true }
foreach ($rec in $script:Cmds) { if ($rec.Info.Name -eq 'Stop-Computer') { $powerOff = $true } }
if ($powerOff) {
Set-Block 3 'command shuts down, powers off, or hibernates the endpoint. Tanium cannot start it again. Use a restart instead (shutdown /r /t 0 or Restart-Computer -Force).'
}
Stop-IfBlocked
# ----- 4. Security-agent protection ----------------------------------
$AgentVendor = '(?i)crowdstrike|falcon|csagent|cstray|csuninstalltool|cyberark|cybr|tanium'
$agentVerbHit = $false
$AgentVerbAst = @('Stop-Service', 'Remove-Service', 'Suspend-Service', 'Restart-Service', 'Stop-Process',
'Invoke-WmiMethod', 'Invoke-CimMethod', 'Remove-WmiObject', 'Remove-CimInstance', 'Uninstall-Package')
$ServiceValue = 'Name', 'DisplayName', 'InputObject', 'Include', 'Exclude', 'StartupType', 'Status', 'Description', 'ComputerName', 'Credential'
$ServiceSwitch = 'Force', 'PassThru', 'NoWait'
$ProcessValue = 'Name', 'Id', 'InputObject'
$serviceTargets = @(); $processTargets = @()
function Get-LiteralList {
param($Bound, [string[]]$Keys)
$out = @()
foreach ($k in $Keys) {
if (-not $Bound.ContainsKey($k)) { continue }
foreach ($a in @($Bound[$k].ToArray())) { $x = Get-Literal $a; if (-not $x.Dynamic) { $out += @($x.Values | Where-Object { $_ }) } }
}
return $out
}
foreach ($rec in $script:Cmds) {
$name = $rec.Info.Name; $leaf = $rec.Info.Leaf; $c = $rec.Cmd
if ($name -in $AgentVerbAst) { $agentVerbHit = $true }
if ($name -eq 'Set-Service') {
# Set-Service is a "disable" verb unless it clearly only enables or starts the service
$b = Get-BoundArgs $c $ServiceValue $ServiceSwitch @{ StartMode = 'StartupType'; SM = 'StartupType'; ST = 'StartupType' }
$want = @(Get-LiteralList $b @('StartupType', 'Status'))
$given = 0
foreach ($k in 'StartupType', 'Status') { if ($b.ContainsKey($k)) { $given += $b[$k].Count } }
$enableOnly = ($given -gt 0 -and $want.Count -eq $given -and
@($want | Where-Object { $_ -notmatch '(?i)^(Automatic|AutomaticDelayedStart|Manual|Running)$' }).Count -eq 0)
if (-not $enableOnly) { $agentVerbHit = $true }
$serviceTargets += @(Get-LiteralList $b @('Name', 'DisplayName', '_pos'))
}
if ($name -in 'Stop-Service', 'Restart-Service', 'Suspend-Service', 'Remove-Service') {
$b = Get-BoundArgs $c $ServiceValue $ServiceSwitch @{}
$names = @(Get-LiteralList $b @('Name', 'DisplayName', '_pos'))
if ($names.Count -eq 0) {
$src = Get-PipelineSource $c
if ($src -is [System.Management.Automation.Language.CommandAst] -and (Get-AstCmdInfo $src).Name -eq 'Get-Service') {
$names = @(Get-LiteralList (Get-BoundArgs $src $ServiceValue $ServiceSwitch @{}) @('Name', 'DisplayName', '_pos'))
}
}
$serviceTargets += $names
}
if ($name -eq 'Stop-Process') {
$b = Get-BoundArgs $c $ProcessValue @('Force', 'PassThru') @{ ProcessName = 'Name'; PID = 'Id' }
$names = @(Get-LiteralList $b @('Name', 'Id', '_pos'))
if ($names.Count -eq 0) {
$src = Get-PipelineSource $c
if ($src -is [System.Management.Automation.Language.CommandAst] -and (Get-AstCmdInfo $src).Name -eq 'Get-Process') {
$names = @(Get-LiteralList (Get-BoundArgs $src $ProcessValue @('FileVersionInfo', 'Module', 'IncludeUserName') @{ ProcessName = 'Name'; PID = 'Id' }) @('Name', 'Id', '_pos'))
}
}
$processTargets += $names
}
if ($leaf -in 'taskkill', 'tskill') {
for ($i = 1; $i -lt $c.CommandElements.Count; $i++) {
$x = Get-Literal $c.CommandElements[$i]
if (-not $x.Dynamic) { foreach ($v in $x.Values) { if ($v -and $v -notmatch '^[/-]') { $processTargets += $v } } }
}
}
if ($leaf -in 'net', 'net1', 'sc') {
$words = @()
for ($i = 1; $i -lt $c.CommandElements.Count; $i++) { $x = Get-Literal $c.CommandElements[$i]; if (-not $x.Dynamic) { $words += @($x.Values) } }
for ($i = 0; $i -lt $words.Count - 1; $i++) {
if ($words[$i] -match '(?i)^(stop|pause|delete|config|failure|sdset)$') { $serviceTargets += $words[$i + 1]; break }
}
}
}
$NativeAgentVerb = '(?i)\bnet1?(\.exe)?\s+(stop|pause)\b|\bsc(\.exe)?\s+(\\\\\S+\s+)?(stop|delete|pause|sdset|failure)\b|\btaskkill\b|\btskill\b|\bwmic(\.exe)?\b.*\b(call|delete)\b|\bmsiexec(\.exe)?\b.*[/-](x|uninstall)\b|\w*unins\w*\.exe|(?<![\w\\])[/-]uninstall\b|\.(Kill|Terminate|StopService|PauseService|Uninstall|ChangeStartMode|Delete)\s*\(|\b(Stop-Service|Stop-Process|Restart-Service|Suspend-Service|Remove-Service|Uninstall-Package)\b'
if ($DecodedCommand -match $NativeAgentVerb) { $agentVerbHit = $true }
# sc config is a "disable" verb unless it only sets the service back to automatic start
if ($DecodedCommand -match '(?i)\bsc(\.exe)?\s+(\\\\\S+\s+)?config\b' -and $DecodedCommand -notmatch '(?i)\bstart=\s*(auto|delayed-auto)\b') { $agentVerbHit = $true }
if ($agentVerbHit -and ($DecodedCommand -match $AgentVendor)) {
Set-Block 5 'command targets a protected security agent (CrowdStrike, Tanium, or CyberArk) with a stop/disable/uninstall action.'
}
# The name typed may not contain a vendor word (a wildcard, a PID, a binary such as vf_agent).
# Look up what it really points at on this computer and test that.
if ($agentVerbHit -and -not $script:BlockCode) {
foreach ($t in @($serviceTargets | Where-Object { $_ } | Select-Object -Unique)) {
$svc = @()
try { $svc += @(Get-Service -Name $t -ErrorAction SilentlyContinue) } catch { }
try { $svc += @(Get-Service -DisplayName $t -ErrorAction SilentlyContinue) } catch { }
foreach ($s in $svc) {
$img = ''
try { $img = [string](Get-ItemProperty -LiteralPath "HKLM:\SYSTEM\CurrentControlSet\Services\$($s.Name)" -Name ImagePath -ErrorAction SilentlyContinue).ImagePath } catch { }
if ("$($s.Name) | $($s.DisplayName) | $img" -match $AgentVendor) {
Set-Block 5 "command targets the service '$($s.Name)' (typed as '$t'), which belongs to a protected security agent (CrowdStrike, Tanium, or CyberArk)."
}
}
}
foreach ($t in @($processTargets | Where-Object { $_ } | Select-Object -Unique)) {
$procs = @()
try {
if ($t -match '^\d+$') { $procs += @(Get-Process -Id ([int]$t) -ErrorAction SilentlyContinue) }
else { $procs += @(Get-Process -Name ($t -replace '(?i)\.exe$', '') -ErrorAction SilentlyContinue) }
} catch { }
foreach ($p in $procs) {
$path = ''; $company = ''
try { $path = [string]$p.Path } catch { }
try { $company = [string]$p.Company } catch { }
if ("$($p.Name) | $path | $company" -match $AgentVendor) {
Set-Block 5 "command targets the process '$($p.Name)' (typed as '$t'), which belongs to a protected security agent (CrowdStrike, Tanium, or CyberArk)."
}
}
}
# msiexec /x {GUID}: look the product code up in both registry views
if ($DecodedCommand -match '(?i)\bmsiexec(\.exe)?\b.*[/-](x|uninstall)\b') {
foreach ($m in [regex]::Matches($DecodedCommand, '\{[0-9A-Fa-f]{8}-(?:[0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}\}')) {
foreach ($view in 'Registry64', 'Registry32') {
try {
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', $view)
$k = $base.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + $m.Value)
if ($k) {
$label = "$($k.GetValue('DisplayName')) | $($k.GetValue('Publisher'))"
if ($label -match $AgentVendor) {
Set-Block 5 "command uninstalls product $($m.Value) ($($k.GetValue('DisplayName'))), which is a protected security agent (CrowdStrike, Tanium, or CyberArk)."
}
}
} catch { }
}
}
}
}
Stop-IfBlocked
# ----- 5. Run ---------------------------------------------------------
if ($Mode -eq 'Audit') {
Write-Log ('{0,-14}the checks passed. Run mode would run the command.' -f 'WOULD RUN')
Complete-Run 0 'Summary (Audit, nothing changed): would run=1; blocked=0'
}
Write-Log ('{0,-14}the checks passed. Output follows.' -f 'RUNNING')
$exitCode = 0
$script:RunError = $null
$script:OutTotal = 0
$fileLines = New-Object System.Collections.Generic.List[string]
$global:LASTEXITCODE = 0
# >>> EXECUTE-BEGIN (test tools swap this block out to build a copy that never runs the command)
try {
$sb = [scriptblock]::Create($DecodedCommand)
# The output is formatted here (Out-String), so table output is never lost when the
# script exits. Write-Host output of the command (stream 6) is included. The inner
# try/catch lets the output printed before an error reach the log as well.
# Blank lines are dropped so they do not use up the action log lines.
& { try { & $sb } catch { $script:RunError = $_ } } 6>&1 |
ForEach-Object { if ($_ -is [System.Management.Automation.InformationRecord]) { [string]$_.MessageData } else { $_ } } |
Out-String -Stream -Width 250 |
ForEach-Object {
$text = ([string]$_).TrimEnd()
if ($text -ne '') {
$script:OutTotal++
if ($script:OutTotal -le $MaxActionLogOutputLines) { Write-Host $text }
if ($script:OutTotal -le $MaxFileOutputLines) { $fileLines.Add($text) }
}
}
if ($global:LASTEXITCODE) { $exitCode = [int]$global:LASTEXITCODE }
}
catch {
$script:RunError = $_
}
# <<< EXECUTE-END
try { if ($fileLines.Count -gt 0) { Add-Content -LiteralPath $LogFile -Value $fileLines -Encoding UTF8 } } catch { }
Write-Log ('Output lines: {0}' -f $script:OutTotal) -FileOnly
if ($script:OutTotal -gt $MaxActionLogOutputLines) {
Write-Log ('{0,-14}the action log shows the first {1} of {2} output lines. The log file {3} has up to {4}.' -f 'TRUNCATED', $MaxActionLogOutputLines, $script:OutTotal, $LogFile, $MaxFileOutputLines) 'WARN'
}
if ($script:RunError) {
Write-Log ('{0,-14}the command stopped with an error: {1}' -f 'FAILED', $script:RunError) 'ERROR'
Complete-Run 1 'Summary (Run): ran=1; failed=1'
}
if ($exitCode -ne 0) {
Write-Log ('{0,-14}the command returned exit code {1}.' -f 'FAILED', $exitCode) 'ERROR'
Complete-Run 1 ('Summary (Run): ran=1; failed=1; command exit code={0}' -f $exitCode)
}
Write-Log ('{0,-14}the command returned exit code 0.' -f 'RAN')
Complete-Run 0 'Summary (Run): ran=1; failed=0'
#!/bin/bash
# ---------------------------------------------------------------------------
# runcommand.sh
# Break-glass package: checks one operator-supplied shell command and, in Run
# mode, runs it in bash.
# Built for a Tanium action package. For Linux and macOS.
# Tanium runs it as the client user, normally root.
#
# SECURITY MODEL: the real control is the content set and RBAC that limit who
# can deploy this package. The checks prevent accidents. They are a list of
# known patterns, not a security boundary, and weaker than the Windows checks
# (there is no real shell parser). A trusted operator who wants to get around
# them can. Do not widen deploy rights because the checks exist.
#
# Tanium command line:
# /bin/bash runcommand.sh "$1" "$2"
#
# Parameters (positional):
# $1 Mode Audit = run the checks and report, run nothing (default)
# Run = run the checks, then run the command if they pass
# $2 Command The shell command to run (bash). Required.
#
# Exit codes:
# 0 Finished. Run: the command ran and returned 0. Audit: always 0
# (read the BLOCKED or WOULD RUN line).
# 1 The command ran and returned a non-zero exit code. The log line gives
# the command's own code ("systemctl status" returns 3 for a stopped unit).
# 2 A parameter was wrong (Mode, empty command, the value was split, or a
# NUL byte). Nothing ran.
# 3 Stopped by a check: protected system path, or a raw disk or file
# system write. Nothing ran.
# 4 Unexpected problem (a temp file could not be made). Nothing ran.
# 5 Stopped by a check: protected security agent. Nothing ran.
# 6 Stopped by a check: decode-and-run command. Nothing ran.
# The first check that trips decides the code.
#
# Log:
# The Tanium action log shows the important lines and the first 60 lines of
# the command's output (standard output and errors together), because the
# console shows about 100 lines. Every line, with up to 5000 output lines,
# also goes to /var/log/runcommand.log when the script can write there.
# The command is logged as typed. A password or token in it is logged too.
#
# Written for bash 3.2 and later (macOS ships 3.2). Only POSIX regex classes
# are used with grep, no \b or \s.
# ---------------------------------------------------------------------------
set -o pipefail
set -f # no filename expansion inside this wrapper. The command itself runs in its own bash.
SCRIPT_NAME="runcommand"
SCRIPT_VERSION="2.0.0"
HOST=$(hostname)
LOG_FILE="/var/log/runcommand.log"
# How many lines of the command's output to show in the Tanium action log, and
# to keep in the log file. Keep the first number well under 100.
MAX_ACTION_LOG_OUTPUT_LINES=60
MAX_FILE_OUTPUT_LINES=5000
# ----- logging and exit helpers ---------------------------------------
# Never call wrong_input, block or finish inside $( ) or a pipe: they must
# exit the main shell.
# The log file is used only when it is a normal file (not a link) that this
# script can write, in a folder that only root can write. Over 1 MB, one old
# copy is kept.
LOG_FD_OK=0
if [ -d /var/log ] && [ -w /var/log ] && [ ! -L "$LOG_FILE" ]; then
if [ -f "$LOG_FILE" ] && [ "$(wc -c < "$LOG_FILE" 2>/dev/null || echo 0)" -gt 1048576 ]; then
mv -f "$LOG_FILE" "$LOG_FILE.old" 2>/dev/null
fi
if exec 3>>"$LOG_FILE"; then LOG_FD_OK=1; fi
fi 2>/dev/null
# log: action log and log file. log_file_only: log file only.
log() {
local line
line="$(date '+%Y-%m-%d %H:%M:%S') $*"
printf '%s\n' "$line"
if [ "$LOG_FD_OK" -eq 1 ]; then printf '%s\n' "$line" >&3; fi
}
log_file_only() {
if [ "$LOG_FD_OK" -eq 1 ]; then printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >&3; fi
}
pad() { printf '%-14s' "$1"; }
# finish CODE [SUMMARY]: writes the summary and the last line, then exits.
finish() {
if [ -n "$2" ]; then log "$2"; fi
log "===== Finished with exit code $1 ====="
exit "$1"
}
wrong_input() {
log "ERROR: $(pad 'WRONG INPUT')$1 Nothing ran."
case "$MODE" in
Audit|Run) finish 2 "Summary ($MODE): wrong input, nothing ran" ;;
*) finish 2 "Summary: wrong input, nothing ran" ;;
esac
}
# block CODE TEXT: a check stopped the command. Audit mode always exits 0.
block() {
log "WARNING: $(pad BLOCKED)$2"
if [ "$MODE" = "Audit" ]; then finish 0 "Summary (Audit, nothing changed): would run=0; blocked=1"; fi
finish "$1" "Summary (Run): blocked=1; nothing ran"
}
lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
# ----- 1. URL-decode (matches .NET UnescapeDataString: '+' stays '+') -
# Only %XX with two hex digits is decoded. A real backslash is kept as typed
# (the old decoder passed the text through printf %b, which turned \n, \t and
# \c into control actions if a backslash ever arrived unencoded).
urldecode() {
local s="${1//\\/\\\\}"
s="$(printf '%s' "$s" | sed 's/%\([0-9A-Fa-f][0-9A-Fa-f]\)/\\x\1/g')"
printf '%b' "$s"
}
# ----- 0. Parameters ----------------------------------------------------
# Decodes one parameter, strips spaces and quotes at both ends, and falls back
# to the default when the value is empty. Used for Mode. The command itself is
# decoded only, because a command can start or end with a quote.
get_param() {
local value
value="$(urldecode "$1" | sed -e "s/^[[:space:]\"']*//" -e "s/[[:space:]\"']*\$//")"
if [ -n "$value" ]; then printf '%s' "$value"; else printf '%s' "$2"; fi
}
MODE="$(get_param "$1" "Audit")"
RAW="$2"
# A NUL byte cannot be held in a shell variable. Such a value is not decoded; it is refused below.
case "$RAW" in
*%00*) CMD="$RAW" ;;
*) CMD="$(urldecode "$RAW")" ;;
esac
log "===== $SCRIPT_NAME $SCRIPT_VERSION started on $HOST ====="
# The command is logged as typed, so a secret in it is logged too.
log "Settings: mode=$MODE; command=$CMD"
case "$(lower "$MODE")" in
audit) MODE="Audit" ;;
run) MODE="Run" ;;
*) wrong_input "Mode must be Audit or Run. Got: $MODE." ;;
esac
if [ "$#" -gt 2 ]; then
wrong_input "the script received $# values instead of 2. The command was split before it reached the script, so the quoting or URL-encoding broke."
fi
case "$RAW" in
*%00*) wrong_input "the command contains a NUL byte (%00)." ;;
esac
if [ -z "${CMD//[[:space:]]/}" ]; then
wrong_input "the command is empty."
fi
# lowercase, whitespace-collapsed copy, for matching only (WS keeps the case)
WS="$(printf '%s' "$CMD" | tr -s '[:space:]' ' ')"
LC="$(lower "$WS")"
B='(^|[^[:alnum:]_])' # word start
E='([^[:alnum:]_]|$)' # word end
# B and E each consume one character, so "systemctl stop" needs two spaces between
# the words for E and B to both match. The copies used for matching get every space doubled.
LCM=" $(printf '%s' "$LC" | sed 's/ / /g') "
WSM=" $(printf '%s' "$WS" | sed 's/ / /g') "
has() { printf '%s' "$LCM" | grep -Eq -- "$1"; }
has_cs() { printf '%s' "$WSM" | grep -Eq -- "$1"; }
# ----- 2. Hard blocks (decode-and-execute) ---------------------------
if has "base64[^|;&]*[[:space:]](-[a-z]*d[a-z]*|--decode)${E}" && \
has "\\|[[:space:]]*(sudo[[:space:]]+)?([a-z0-9_./-]*/)?(ba|da|z|k)?sh${E}|${B}(eval|source)${E}|${B}(ba|da|z|k)?sh[[:space:]]+-[a-z]*c${E}|<\\("; then
block 6 "decode-and-execute pattern is not allowed."
fi
# ----- protected-path lists (all lowercase, no spaces) ----------------
# ALLOWED : may be deleted even though the folder above is protected
# SUBTREE : the folder and everything in it
# EXACT : the folder itself and "folder/*", but not single items inside it
# AGENT : security agent folders (reported with exit code 4)
# A path is also protected when it is a PARENT of a protected folder
# (/var holds /var/lib), and when a wildcard in it could match one (/e*).
ALLOWED_ROOTS="/usr/local /var/lib/apt/lists /dev/shm"
SUBTREE_ROOTS="/bin /sbin /boot /lib /lib32 /lib64 /libx32 /usr /etc /var/lib /var/db /dev /proc /sys /system /library/launchdaemons /private/etc /private/var/db"
EXACT_ROOTS="/var /home /root /opt /srv /mnt /media /run /private /private/var /users /applications /library /volumes"
AGENT_ROOTS="/opt/crowdstrike /opt/tanium /opt/cyberark /opt/carkaim /library/tanium /library/cs /applications/falcon.app"
AGENT_VENDOR='crowdstrike|falcon|cyberark|cybr|carkaim|tanium'
# When Tanium runs this, the script sits in <TaniumClient>/Downloads/Action_<id>.
# Protect the client folder wherever it is installed, but let the operator
# clean this action's own folder.
SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd)"
case "$SCRIPT_DIR" in
*" "*) ;;
*/Downloads/Action_*)
AGENT_ROOTS="$AGENT_ROOTS $(lower "${SCRIPT_DIR%/Downloads/Action_*}")"
ALLOWED_ROOTS="$ALLOWED_ROOTS $(lower "$SCRIPT_DIR")"
;;
esac
split_path() { # $1 = normalized absolute path. Fills SEGS with its parts.
local IFS=/
SEGS=($1)
SEGS=("${SEGS[@]:1}")
}
norm_path() { # collapses //, /./ and /../ . Result in NP.
local p="$1" out="" seg IFS=/
for seg in $p; do
case "$seg" in
''|.) ;;
..) out="${out%/*}" ;;
*) out="$out/$seg" ;;
esac
done
[ -z "$out" ] && out="/"
NP="$out"
}
canon_path() { # resolves symlinks in the part before the first wildcard. Result in CP, or empty.
CP=""
command -v realpath >/dev/null 2>&1 || return 0
local p="$1" prefix="" rest="" seg glob=0 r IFS=/
for seg in $p; do
[ -z "$seg" ] && continue
if [ "$glob" -eq 0 ]; then case "$seg" in *[*?[]*) glob=1 ;; esac; fi
if [ "$glob" -eq 0 ]; then prefix="$prefix/$seg"; else rest="$rest/$seg"; fi
done
[ -z "$prefix" ] && return 0
r="$(realpath -m -- "$prefix" 2>/dev/null || realpath -- "$prefix" 2>/dev/null)"
if [ -n "$r" ] && [ "$r" != "$prefix" ]; then CP="$r$rest"; fi
return 0
}
root_overlap() { # compares PSEG (typed path) with RSEG (protected root).
# OV: 0 no overlap, 1 typed path is the root or a parent of it, 2 typed path is inside the root
local n=${#PSEG[@]} m=${#RSEG[@]} k i
k=$n; [ "$m" -lt "$k" ] && k=$m
for ((i = 0; i < k; i++)); do
# the right side is a glob pattern on purpose: a typed "e*" matches the root "etc"
[[ "${RSEG[i]}" == ${PSEG[i]} ]] || { OV=0; return 0; }
done
if [ "$n" -le "$m" ]; then OV=1; else OV=2; fi
return 0
}
check_path() { # $1 = lowercase normalized path, $2 = rm | find. Returns 0 and sets KIND (os/agent) when protected.
local p="$1" mode="$2" r i n m last same
KIND=""
split_path "$p"; PSEG=("${SEGS[@]}")
n=${#PSEG[@]}
for r in $ALLOWED_ROOTS; do # allow wins
split_path "$r"; RSEG=("${SEGS[@]}")
m=${#RSEG[@]}
if [ "$n" -ge "$m" ]; then
same=1
for ((i = 0; i < m; i++)); do [ "${PSEG[i]}" = "${RSEG[i]}" ] || { same=0; break; }; done
[ "$same" -eq 1 ] && return 1
fi
done
if [ "$n" -eq 0 ]; then KIND=os; return 0; fi # "/" itself
last="${PSEG[n-1]}"
for r in $SUBTREE_ROOTS; do
split_path "$r"; RSEG=("${SEGS[@]}")
root_overlap
if [ "$OV" -ne 0 ]; then KIND=os; return 0; fi
done
for r in $EXACT_ROOTS; do
split_path "$r"; RSEG=("${SEGS[@]}")
m=${#RSEG[@]}
root_overlap
if [ "$OV" -eq 1 ]; then
# "find /home -name x -delete" is not the same as deleting /home, so find may start at an EXACT root
if [ "$mode" = find ] && [ "$n" -eq "$m" ]; then :; else KIND=os; return 0; fi
elif [ "$OV" -eq 2 ] && [ "$mode" != find ] && [ "$n" -eq $((m + 1)) ] && [ "$last" = "*" ]; then
KIND=os; return 0
fi
done
for r in $AGENT_ROOTS; do
split_path "$r"; RSEG=("${SEGS[@]}")
root_overlap
if [ "$OV" -ne 0 ]; then KIND=agent; return 0; fi
done
return 1
}
# ----- command reader --------------------------------------------------
# Not a real shell parser. It splits the command into words (honouring quotes
# and backslashes), finds rm / unlink / rmdir / shred / find -delete / rsync
# --delete / cd / kill, and looks inside sh -c "..." and eval "...".
SEP=$'\001' # marks ; | & ( ) < > and newlines
tokenize() { # $1 = text. Fills TOK.
local s="$1" n=${#1} i c nx w="" inw=0 q=""
TOK=()
for ((i = 0; i < n; i++)); do
c="${s:i:1}"
if [ "$q" = "'" ]; then
if [ "$c" = "'" ]; then q=""; else w+="$c"; fi
continue
fi
if [ "$q" = '"' ]; then
case "$c" in
'"') q="" ;;
'\') nx="${s:i+1:1}"
case "$nx" in '"'|'\'|'$'|'`') w+="$nx"; i=$((i + 1)) ;; *) w+="$c" ;; esac ;;
'`') w+='$' ;; # command substitution: mark the word as dynamic
*) w+="$c" ;;
esac
continue
fi
case "$c" in
"'"|'"') q="$c"; inw=1 ;;
'\') nx="${s:i+1:1}"; i=$((i + 1))
if [ "$nx" != $'\n' ]; then w+="$nx"; inw=1; fi ;;
' '|$'\t')
if [ "$inw" -eq 1 ]; then TOK+=("$w"); w=""; inw=0; fi ;;
';'|'|'|'&'|'('|')'|'<'|'>'|$'\n'|$'\r')
if [ "$inw" -eq 1 ]; then TOK+=("$w"); w=""; inw=0; fi
TOK+=("$SEP") ;;
'`') w+='$'; TOK+=("$w"); w=""; inw=0; TOK+=("$SEP") ;;
'#') if [ "$inw" -eq 0 ]; then
while [ "$i" -lt "$n" ] && [ "${s:i:1}" != $'\n' ]; do i=$((i + 1)); done
i=$((i - 1))
else w+="$c"; fi ;;
*) w+="$c"; inw=1 ;;
esac
done
if [ "$inw" -eq 1 ]; then TOK+=("$w"); fi
return 0
}
DEL_ARGS=() # paths handed to rm / unlink / rmdir / shred / srm, and rsync --delete targets
FIND_ROOTS=() # start folders of a find that deletes
CD_TARGETS=() # cd / pushd targets, in order
ALL_WORDS=() # every word seen at any depth, for the conservative scan
KILL_PIDS=() # numeric arguments of kill
delete_seen=0 # a delete command was found
delete_unbound=0 # a delete whose paths arrive on stdin (xargs rm)
seg_end() { # closes one command. Uses the locals of scan_text (bash dynamic scope).
local lastarg
if [ "$infind" -eq 1 ] && [ "$find_deletes" -eq 1 ]; then
if [ "${#froots[@]}" -eq 0 ]; then froots=("."); fi
FIND_ROOTS+=("${froots[@]}")
delete_seen=1
fi
if [ "$mode" = rsync ] && [ "$rs_delete" -eq 1 ] && [ "${#rs_args[@]}" -ge 2 ]; then
lastarg="${rs_args[${#rs_args[@]}-1]}"
case "$lastarg" in
*:*) ;; # remote target: not checked
*) DEL_ARGS+=("$lastarg"); delete_seen=1 ;;
esac
fi
if [ "$mode" = cd ] && [ "$cd_seen" -eq 0 ]; then CD_TARGETS+=("${HOME:-/root}"); fi # plain "cd" goes home
expect=1; mode=""; wrapper=""; optsdone=0; skipnext=0; chroot_dir=0
infind=0; inexec=0; find_deletes=0; find_roots_open=0; via_xargs=0; cd_seen=0
froots=(); rs_args=(); rs_delete=0
return 0
}
scan_text() { # $1 = command text, $2 = nesting depth
local depth="$2"
[ "$depth" -gt 6 ] && return 0
tokenize "$1"
local -a W=("${TOK[@]}")
local n=${#W[@]} i=0 w lw rest
local expect=1 mode="" wrapper="" optsdone=0 skipnext=0 chroot_dir=0
local infind=0 inexec=0 find_deletes=0 find_roots_open=0 via_xargs=0 cd_seen=0 rs_delete=0
local -a froots=() rs_args=()
while [ "$i" -lt "$n" ]; do
w="${W[i]}"; i=$((i + 1))
if [ "$w" = "$SEP" ]; then seg_end; continue; fi
ALL_WORDS+=("$w")
if [ "$skipnext" -eq 1 ]; then skipnext=0; continue; fi
if [ "$expect" -eq 1 ]; then
# --- still looking for the command word
case "$w" in
-*)
# an option of a wrapper such as sudo, xargs, bash, timeout
case "$wrapper" in
sh|su)
case "$w" in
--*) ;;
-*c*) # sh -c "text": read the text as a command
if [ "$i" -lt "$n" ] && [ "${W[i]}" != "$SEP" ]; then
ALL_WORDS+=("${W[i]}")
scan_text "${W[i]}" $((depth + 1))
i=$((i + 1))
fi
mode=other; expect=0 ;;
esac ;;
sudo) case "$w" in -u|-g|-U|-h|-p|-C|-r|-t|-T|-D) skipnext=1 ;; esac ;;
xargs) case "$w" in -n|-I|-P|-L|-d|-a|-s|-E) skipnext=1 ;; esac ;;
nice) case "$w" in -n) skipnext=1 ;; esac ;;
ionice) case "$w" in -c|-n|-p) skipnext=1 ;; esac ;;
timeout) case "$w" in -s|-k) skipnext=1 ;; esac ;;
env) case "$w" in -u|-C) skipnext=1 ;; esac ;;
esac
continue ;;
*=*) continue ;; # VAR=value in front of the command
esac
if [ -n "$wrapper" ]; then
case "$w" in
[0-9]|[0-9]*[0-9smhd]) case "$w" in *[!0-9.smhd]*) ;; *) continue ;; esac ;; # timeout 30s, nice 10
esac
if [ "$wrapper" = chroot ] && [ "$chroot_dir" -eq 0 ]; then chroot_dir=1; continue; fi
if [ "$wrapper" = su ]; then continue; fi # su - user -c "..."
fi
lw="$(lower "${w##*/}")"
case "$lw" in
sudo|xargs|nice|ionice|timeout|env|chroot)
wrapper="$lw"; [ "$lw" = xargs ] && via_xargs=1; continue ;;
doas|nohup|time|command|exec|builtin|busybox|stdbuf|setsid|watch|then|else|elif|do|if|while|until|'!'|'{')
wrapper=gen; continue ;;
sh|bash|dash|zsh|ksh|ash)
wrapper=sh; continue ;;
su|runuser)
wrapper=su; continue ;;
eval)
rest=""
while [ "$i" -lt "$n" ] && [ "${W[i]}" != "$SEP" ]; do
ALL_WORDS+=("${W[i]}"); rest="$rest ${W[i]}"; i=$((i + 1))
done
scan_text "$rest" $((depth + 1))
mode=other; expect=0 ;;
rm|unlink|rmdir|shred|srm)
mode=del; expect=0; optsdone=0; delete_seen=1
[ "$via_xargs" -eq 1 ] && delete_unbound=1 ;;
find)
mode=find; expect=0; infind=1; find_roots_open=1; find_deletes=0; froots=() ;;
cd|pushd)
mode=cd; expect=0; cd_seen=0 ;;
rsync)
mode=rsync; expect=0; rs_args=(); rs_delete=0 ;;
kill)
mode=kill; expect=0 ;;
*)
mode=other; expect=0 ;;
esac
continue
fi
# --- arguments of the command
if [ "$inexec" -eq 1 ] && { [ "$w" = ";" ] || [ "$w" = "+" ]; }; then
mode=find; inexec=0; continue # end of find -exec ... \;
fi
case "$mode" in
del)
if [ "$inexec" -eq 1 ] && [ "$w" = "{}" ]; then find_deletes=1; continue; fi
if [ "$optsdone" -eq 0 ]; then
if [ "$w" = "--" ]; then optsdone=1; continue; fi
case "$w" in -*) continue ;; esac
fi
DEL_ARGS+=("$w") ;;
find)
if [ "$find_roots_open" -eq 1 ]; then
case "$w" in
-*|'!'|'(') find_roots_open=0 ;;
*) froots+=("$w"); continue ;;
esac
fi
case "$w" in
-delete) find_deletes=1 ;;
-exec|-execdir|-ok|-okdir) expect=1; wrapper=""; inexec=1 ;;
esac ;;
cd)
if [ "$cd_seen" -eq 0 ]; then
case "$w" in
-) CD_TARGETS+=('$OLDPWD'); cd_seen=1 ;;
-*) ;;
*) CD_TARGETS+=("$w"); cd_seen=1 ;;
esac
fi ;;
rsync)
case "$w" in
--delete*|--del|--remove-source-files) rs_delete=1 ;;
-*) ;;
*) rs_args+=("$w") ;;
esac ;;
kill)
case "$w" in
-*|*[!0-9]*) ;;
*) KILL_PIDS+=("$w") ;;
esac ;;
esac
done
seg_end
return 0
}
BASES=("$PWD") # folders a relative path could be resolved against
cd_dynamic=0 # a cd whose target this script cannot read
resolve_arg() { # $1 = path as typed. Fills RES with absolute normalized forms. Sets RES_UNKNOWN=1 for ~user.
local a="$1" b
RES=(); RES_UNKNOWN=0
# {a,b} and {1..3} can expand to anything in the list: treat them as a wildcard
a="$(printf '%s' "$a" | sed 's/{[^{}]*[,.][^{}]*}/*/g')"
case "$a" in
"~") a="${HOME:-/root}" ;;
"~/"*) a="${HOME:-/root}/${a#??}" ;;
"~"*) RES_UNKNOWN=1; return 0 ;;
esac
case "$a" in
/*) norm_path "$a"; RES=("$NP") ;;
*) for b in "${BASES[@]}"; do norm_path "$b/$a"; RES+=("$NP"); done ;;
esac
return 0
}
HIT_KIND=""; HIT_TYPED=""; HIT_PATH=""; DYNAMIC_ARG=""; REL_AFTER_CD=""
check_delete_arg() { # $1 = argument as typed, $2 = rm | find. Records the first protected hit.
local a="$1" mode="$2" p cand low
[ -n "$HIT_KIND" ] && return 0
case "$a" in
*'$'*) [ -z "$DYNAMIC_ARG" ] && DYNAMIC_ARG="$a"; return 0 ;;
esac
resolve_arg "$a"
if [ "$RES_UNKNOWN" -eq 1 ]; then [ -z "$DYNAMIC_ARG" ] && DYNAMIC_ARG="$a"; return 0; fi
case "$a" in
/*|"~"*) ;;
*) if [ "$cd_dynamic" -eq 1 ] && [ -z "$REL_AFTER_CD" ]; then REL_AFTER_CD="$a"; fi ;;
esac
for p in "${RES[@]}"; do
canon_path "$p"
for cand in "$p" "$CP"; do
[ -z "$cand" ] && continue
low="$(lower "$cand")"
if check_path "$low" "$mode"; then
HIT_KIND="$KIND"; HIT_TYPED="$a"; HIT_PATH="$cand"
return 0
fi
done
done
return 0
}
scan_text "$CMD" 0
# folders a relative path could mean: the current folder plus every cd target
for t in "${CD_TARGETS[@]}"; do
case "$t" in
*'$'*) cd_dynamic=1; continue ;;
esac
resolve_arg "$t"
if [ "$RES_UNKNOWN" -eq 1 ]; then cd_dynamic=1; continue; fi
for p in "${RES[@]}"; do BASES+=("$p"); done
done
# ----- 3. Delete protection ------------------------------------------
if [ "$delete_seen" -eq 1 ]; then
if has '--no-preserve-root'; then
block 3 "--no-preserve-root is not allowed."
fi
for a in "${DEL_ARGS[@]}"; do check_delete_arg "$a" rm; done
for a in "${FIND_ROOTS[@]}"; do check_delete_arg "$a" find; done
# a delete fed by xargs has no paths of its own: test every absolute path in the command
if [ "$delete_unbound" -eq 1 ]; then
saved_dynamic="$DYNAMIC_ARG"
for a in "${ALL_WORDS[@]}"; do
case "$a" in /*|"~"|"~/"*) check_delete_arg "$a" rm ;; esac
done
DYNAMIC_ARG="$saved_dynamic"
fi
# rm against / or /* (root)
if [ -z "$HIT_KIND" ] && has "${B}rm${E}[^|;&]*[[:space:]](/|/\\*)([[:space:]]|\$)"; then
HIT_KIND=os; HIT_TYPED="/"; HIT_PATH="/"
fi
if [ -n "$HIT_KIND" ]; then
shown="'$HIT_PATH'"
[ "$HIT_TYPED" != "$HIT_PATH" ] && shown="'$HIT_TYPED' (checked as '$HIT_PATH')"
if [ "$HIT_KIND" = agent ]; then
block 5 "command deletes $shown, which belongs to a protected security agent (CrowdStrike, Tanium, or CyberArk)."
fi
block 3 "command deletes $shown, a protected OS path."
fi
if [ -n "$DYNAMIC_ARG" ]; then
block 3 "command deletes '$DYNAMIC_ARG', a path built from a variable or a command substitution, so this script cannot check it."
fi
if [ -n "$REL_AFTER_CD" ]; then
block 3 "command deletes the relative path '$REL_AFTER_CD' after a cd whose target this script cannot read."
fi
fi
# disk / filesystem wipes - blocked outright
disk_hit=0
DISK="${B}(mkfs(\\.[a-z0-9]+)?|wipefs|blkdiscard|lvremove|vgremove|pvremove)${E}"
DISK="$DISK|${B}(zpool|zfs)[[:space:]]+destroy${E}"
DISK="$DISK|${B}parted${E}[^|;&]*[[:space:]](rm|mklabel|mktable)${E}"
DISK="$DISK|${B}cryptsetup${E}[^|;&]*[[:space:]](luksformat|lukserase|erase)${E}"
DISK="$DISK|${B}nvme[[:space:]]+format${E}"
DISK="$DISK|${B}diskutil[[:space:]]+(erasedisk|erasevolume|reformat|zerodisk|randomdisk|secureerase|partitiondisk|apfs[[:space:]]+delete[a-z]*)${E}"
DISK="$DISK|>[[:space:]]*/dev/(sd|nvme|disk|rdisk|vd|xvd|hd|mmcblk|dm-|mapper/|md)"
if has "$DISK"; then disk_hit=1; fi
# sgdisk: -Z/-z/-o wipe, but -O only prints, so this one is case-sensitive
if has_cs "${B}sgdisk${E}[^|;&]*[[:space:]](-z|-Z|-o|--zap|--zap-all|--clear)${E}"; then disk_hit=1; fi
# dd to a device, except the harmless ones (of=/dev/null and friends)
if has "${B}dd${E}"; then
while IFS= read -r target; do
case "$target" in
''|of=/dev/null|of=/dev/zero|of=/dev/full|of=/dev/stdout|of=/dev/stderr|of=/dev/tty*|of=/dev/fd/*|of=/dev/shm/*|of=/dev/random|of=/dev/urandom) ;;
*) disk_hit=1 ;;
esac
done <<EOF
$(printf '%s' "$LC" | grep -Eo 'of=/dev/[^[:space:]|;&]*')
EOF
fi
if [ "$disk_hit" -eq 1 ]; then
block 3 "raw disk/filesystem write (mkfs/dd/wipefs or a partition tool on a device) is not allowed."
fi
# power off. A powered-off endpoint cannot be started again from Tanium. A restart is allowed.
# shutdown with no -r (Linux shutdown powers off by default), poweroff, halt, init 0,
# systemctl poweroff/halt/suspend/hibernate.
# CMDPOS: the word is where a command starts (start of the line, after ; & | ( or a
# backtick, after sudo/doas/nohup/exec, or right after sh -c), so "last -x shutdown" is not a hit.
CMDPOS="(^|[;&|(\`]|sudo|doas|nohup|exec|-c[[:space:]]+[\"']?)[[:space:]]*([^[:space:]]*/)?"
power_off=0
if has "${CMDPOS}(poweroff|halt)${E}|${B}(tel)?init[[:space:]]+0${E}|${B}systemctl${E}[^|;&]*${B}(poweroff|halt|suspend|hibernate|hybrid-sleep|suspend-then-hibernate)${E}"; then
power_off=1
fi
if has "${CMDPOS}shutdown${E}" && ! has "${CMDPOS}shutdown${E}[^|;&]*[[:space:]](-r|--reboot|-c|-k)${E}"; then
power_off=1
fi
if [ "$power_off" -eq 1 ]; then
block 3 "command shuts down, powers off, or suspends the endpoint. Tanium cannot start it again. Use a restart instead (shutdown -r now or reboot)."
fi
# ----- 4. Security-agent protection ----------------------------------
agent_verb=0
VERB="${B}(systemctl|service)${E}[^|;&]*${B}(stop|disable|mask|kill)${E}"
VERB="$VERB|init\\.d/[^[:space:]]+[[:space:]]+stop${E}"
VERB="$VERB|${B}launchctl${E}[^|;&]*${B}(unload|bootout|disable|remove|stop|kill)${E}"
VERB="$VERB|${B}(kill|pkill|killall)${E}"
VERB="$VERB|${B}rpm${E}[^|;&]*[[:space:]](-[a-z]*e[a-z]*|--erase)${E}"
VERB="$VERB|${B}(apt|apt-get|aptitude|yum|dnf|zypper|snap)${E}[^|;&]*${B}(remove|purge|erase|autoremove)${E}"
VERB="$VERB|${B}brew${E}[^|;&]*uninstall|${B}pkgutil${E}[^|;&]*--forget"
VERB="$VERB|${B}chkconfig${E}[^|;&]*[[:space:]](off|--del)${E}|${B}update-rc\\.d${E}[^|;&]*${B}(disable|remove)${E}"
# falconctl -g (read a setting) is allowed. -s (set), -d (delete) and uninstall/unload/disable are not.
VERB="$VERB|${B}falconctl${E}[^|;&]*[[:space:]](-[a-z]*[sd][a-z]*|uninstall|unload|disable)${E}"
if has "$VERB"; then agent_verb=1; fi
# dpkg: -r and -P remove, but -p only prints, so this one is case-sensitive
if has_cs "${B}dpkg${E}[^|;&]*[[:space:]](-r|-P|--remove|--purge)${E}"; then agent_verb=1; fi
if [ "$agent_verb" -eq 1 ] && has "$AGENT_VENDOR"; then
block 5 "command targets a protected security agent (CrowdStrike, Tanium, or CyberArk)."
fi
# kill by PID has no vendor word in it: look the PID up and test what it really is
for pid in "${KILL_PIDS[@]}"; do
pinfo="$(ps -p "$pid" -o args= 2>/dev/null | tr '[:upper:]' '[:lower:]')"
if [ -n "$pinfo" ] && printf '%s' "$pinfo" | grep -Eq -- "$AGENT_VENDOR"; then
block 5 "command kills process $pid, which belongs to a protected security agent (CrowdStrike, Tanium, or CyberArk)."
fi
done
# ----- 5. Run ---------------------------------------------------------
if [ "$MODE" = "Audit" ]; then
log "WOULD RUN the checks passed. Run mode would run the command."
finish 0 "Summary (Audit, nothing changed): would run=1; blocked=0"
fi
log "$(pad RUNNING)the checks passed. Output follows."
out_total=0
rc=0
# >>> EXECUTE-BEGIN (test tools swap this block out to build a copy that never runs the command)
RC_FILE="$(mktemp 2>/dev/null)"
if [ -z "$RC_FILE" ]; then
log "ERROR: could not make a temp file, so the command did not run."
finish 4 "Summary (Run): unexpected problem, nothing ran"
fi
# Standard output and errors of the command, together. Blank lines are dropped so
# they do not use up the action log lines.
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in *[![:space:]]*) ;; *) continue ;; esac
out_total=$((out_total + 1))
if [ "$out_total" -le "$MAX_ACTION_LOG_OUTPUT_LINES" ]; then printf '%s\n' "$line"; fi
if [ "$LOG_FD_OK" -eq 1 ] && [ "$out_total" -le "$MAX_FILE_OUTPUT_LINES" ]; then printf '%s\n' "$line" >&3; fi
done < <(bash -c "$CMD" 2>&1; printf '%s' "$?" > "$RC_FILE")
rc="$(cat "$RC_FILE" 2>/dev/null)"
rm -f "$RC_FILE"
[ -z "$rc" ] && rc=1
# <<< EXECUTE-END
log_file_only "Output lines: $out_total"
if [ "$out_total" -gt "$MAX_ACTION_LOG_OUTPUT_LINES" ]; then
if [ "$LOG_FD_OK" -eq 1 ]; then where="The log file $LOG_FILE has up to $MAX_FILE_OUTPUT_LINES."
else where="There is no log file (the script cannot write $LOG_FILE)."; fi
log "WARNING: $(pad TRUNCATED)the action log shows the first $MAX_ACTION_LOG_OUTPUT_LINES of $out_total output lines. $where"
fi
if [ "$rc" != "0" ]; then
log "ERROR: $(pad FAILED)the command returned exit code $rc."
finish 1 "Summary (Run): ran=1; failed=1; command exit code=$rc"
fi
log "$(pad RAN)the command returned exit code 0."
finish 0 "Summary (Run): ran=1; failed=0"