<# .SYNOPSIS ASR Rules Builder: save, install, inspect, collect telemetry for, and restore a Microsoft Defender Attack Surface Reduction (ASR) policy built at https://asrrules.com/. .DESCRIPTION asr-rules-builder.ps1 is the single PowerShell script behind ASR Rules Builder (by MagicSword). It takes an encoded policy string (base64url of the policy JSON, as produced by the ASR Rules Builder policy builder), validates it strictly, and then: Save Writes \.asr-policy.json (canonical JSON, encoded string, timestamp) and \.install.ps1, a standalone offline install script for that policy. No admin rights needed. This is the default action. Install Shows a plan (current -> new) for every ASR rule, exclusion, Controlled folder access and Network protection setting in the policy, asks for confirmation, writes a JSON backup of the current settings to $env:ProgramData\ASR-Rules-Builder\backups, applies the policy with Add-MpPreference / Set-MpPreference and verifies the result. Requires Windows, an elevated session and the Microsoft Defender PowerShell module. Status Prints the ASR rules, exclusions, Controlled folder access and Network protection settings currently configured on this device. Collect Reads ASR, Controlled folder access and Network protection events (1121, 1122, 1123, 1124, 1125, 1126, 1129 and ASR-related 5007) from the Microsoft-Windows-Windows Defender/Operational log, writes them to a CSV file and prints an analysis (noisiest rules, top processes, paths, users, events per day, audit rules with zero hits). Restore Re-applies a backup written by Install (newest one by default). Only backups owned by Administrators or SYSTEM, in a folder that non-administrators cannot write to, are accepted. Backups live in $env:ProgramData\ASR-Rules-Builder\backups. The script creates ASR-Rules-Builder and backups with an access list that grants only SYSTEM and Administrators (inheritance disabled), repairs that access list when it is looser, and refuses to use either folder when it is a symbolic link or junction or is owned by anyone other than Administrators or SYSTEM. What the script does NOT do: it never downloads anything, never runs input as code (no Invoke-Expression), and never changes rules that are not in the policy. Exit codes: 0 success, 1 validation error (policy or backup rejected), 2 environment problem (not Windows, not elevated, Defender cmdlets missing, log not readable, file write failed, unsafe backup folder), 3 verification mismatch or apply error after Install/Restore, 4 cancelled at the confirmation prompt (or no interactive console to ask; use -Force), 5 Install applied and verified everything it could, but part of the policy could not be applied on this device (for example per-rule exclusions on a Defender build without them). When the script is run from a file (.\asr-rules-builder.ps1) it ends with `exit `. When it is run through the [scriptblock]::Create((irm ...)) one-liner it does not close your PowerShell window; the exit code is left in $LASTEXITCODE instead. Fleet tools that start a new powershell.exe with -Command must append `; exit $LASTEXITCODE`, otherwise the process exit code does not reflect the result. .PARAMETER Action Save (default), Install, Status, Collect or Restore. .PARAMETER Policy The encoded policy string from the ASR Rules Builder policy builder. Required for Save and Install. Optional for Collect (used to list audit-mode rules with zero hits). .PARAMETER OutDir Output folder for Save and Collect. Default: $env:USERPROFILE\ASR-Rules-Builder. .PARAMETER Days Collect look-back window in days, 1-365. Default 30. .PARAMETER Force Skip the Install/Restore confirmation prompt (for Intune, RMM and other fleet tools). .PARAMETER BackupPath Restore: backup JSON to re-apply. Default: newest asr-backup-*.json in $env:ProgramData\ASR-Rules-Builder\backups. .PARAMETER WhatIf Install/Restore: show the plan and change nothing. Save/Collect: print the files that would be written and write nothing. .EXAMPLE & ([scriptblock]::Create((irm 'https://asrrules.com/asr-rules-builder.ps1'))) -Policy '' -Action Install Installs the policy from an elevated PowerShell session after showing the plan and asking "Are you sure you want to install this ASR policy? [y/N]". .EXAMPLE irm 'https://asrrules.com/asr-rules-builder.ps1' -OutFile asr-rules-builder.ps1 Get-FileHash .\asr-rules-builder.ps1 -Algorithm SHA256 .\asr-rules-builder.ps1 -Policy '' -Action Save Inspect-first: download the script, compare the hash with the one shown on the site, then save the policy JSON and a standalone offline install script to $env:USERPROFILE\ASR-Rules-Builder. .EXAMPLE .\asr-rules-builder.ps1 -Policy '' -Action Install -WhatIf Shows the install plan (current mode -> new mode for every setting) and changes nothing. .EXAMPLE powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\asr-rules-builder.ps1 -Policy '' -Action Install -Force Unattended install for fleet tools. Exit code 0 means installed and verified; 5 means installed and verified, but part of the policy could not be applied on this device. .EXAMPLE powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& ([scriptblock]::Create((irm 'https://asrrules.com/asr-rules-builder.ps1'))) -Policy '' -Action Install -Force; exit $LASTEXITCODE" The same through -Command. The trailing `exit $LASTEXITCODE` passes the result to the RMM. .EXAMPLE .\asr-rules-builder.ps1 -Action Status Shows the ASR rules, ASR-only exclusions, Controlled folder access and Network protection settings configured on this device, and warns when they are managed by GPO/MDM. .EXAMPLE .\asr-rules-builder.ps1 -Action Collect -Days 14 -OutDir C:\Temp\ASR Exports the last 14 days of ASR / CFA / Network protection events to C:\Temp\ASR\asr-events--.csv and prints an analysis. .EXAMPLE .\asr-rules-builder.ps1 -Action Restore Shows the newest backup in $env:ProgramData\ASR-Rules-Builder\backups, asks "Are you sure you want to restore this ASR backup? [y/N]" and re-applies it. .EXAMPLE .\asr-rules-builder.ps1 -Action Restore -BackupPath 'C:\ProgramData\ASR-Rules-Builder\backups\asr-backup-20261202-101500.json' -Force Restores a specific backup without prompting. .NOTES ASR Rules Builder by MagicSword. https://github.com/magicsword-io/ASR-Rules-Builder Works on Windows PowerShell 5.1 and PowerShell 7. Licensed under the Apache License 2.0. .LINK https://asrrules.com/ #> [CmdletBinding(SupportsShouldProcess = $true)] param( [ValidateSet('Save', 'Install', 'Status', 'Collect', 'Restore')] [string]$Action = 'Save', [string]$Policy, [string]$OutDir, [ValidateRange(1, 365)] [int]$Days = 30, [switch]$Force, [string]$BackupPath ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' # The script source, used by Save to copy the install functions into the standalone script. # Works both for a file and for a [scriptblock]::Create((irm ...)) invocation. $AsrRulesBuilderSourceAst = $MyInvocation.MyCommand.ScriptBlock.Ast # >>> rule-catalog (kept in sync with site/src/data/rules.ts by scripts/test-rules-sync.mjs) $AsrRuleCatalog = @( @{ Id = '56a863a9-875e-4185-98a7-b882c64b5ce5'; ShortName = 'Vulnerable signed drivers'; Warn = $true; Name = 'Block abuse of exploited vulnerable signed drivers (Device)' } @{ Id = '7674ba52-37eb-4a4f-a9a1-f0f9a1619a2c'; ShortName = 'Adobe Reader child processes'; Warn = $true; Name = 'Block Adobe Reader from creating child processes' } @{ Id = 'd4f940ab-401b-4efc-aadc-ad5f3c50688a'; ShortName = 'Office child processes'; Warn = $true; Name = 'Block all Office applications from creating child processes' } @{ Id = '9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2'; ShortName = 'LSASS credential theft'; Warn = $false; Name = 'Block credential stealing from the Windows local security authority subsystem' } @{ Id = 'be9ba2d9-53ea-4cdc-84e5-9b1eeee46550'; ShortName = 'Email executable content'; Warn = $true; Name = 'Block executable content from email client and webmail' } @{ Id = '01443614-cd74-433a-b99e-2ecdc07bfc25'; ShortName = 'Low-prevalence executables'; Warn = $true; Name = 'Block executable files from running unless they meet a prevalence, age, or trusted list criterion' } @{ Id = '5beb7efe-fd9a-4556-801d-275e5ffc04cc'; ShortName = 'Obfuscated scripts'; Warn = $true; Name = 'Block execution of potentially obfuscated scripts' } @{ Id = 'd3e037e1-3eb8-44c8-a917-57927947596d'; ShortName = 'JS/VBS launching downloads'; Warn = $true; Name = 'Block JavaScript or VBScript from launching downloaded executable content' } @{ Id = '3b576869-a4ec-4529-8536-b80a7769e899'; ShortName = 'Office executable content'; Warn = $true; Name = 'Block Office applications from creating executable content' } @{ Id = '75668c1f-73b5-4cf0-bb93-3ecf5cb7cc84'; ShortName = 'Office code injection'; Warn = $false; Name = 'Block Office applications from injecting code into other processes' } @{ Id = '26190899-1602-49e8-8b27-eb1d0a1ce869'; ShortName = 'Outlook child processes'; Warn = $true; Name = 'Block Office communication application from creating child processes' } @{ Id = 'e6db77e5-3df2-4cf1-b95a-636979351e5b'; ShortName = 'WMI event persistence'; Warn = $true; Name = 'Block persistence through WMI event subscription' } @{ Id = 'd1e49aac-8f56-4280-b9ba-993a6d77406c'; ShortName = 'PSExec and WMI processes'; Warn = $true; Name = 'Block process creations originating from PSExec and WMI commands' } @{ Id = '33ddedf1-c6e0-47cb-833e-de6133960387'; ShortName = 'Safe Mode reboot'; Warn = $true; Name = 'Block rebooting machine in Safe Mode' } @{ Id = 'b2b3f03d-6a65-4f7b-a9c7-1c7ef74a9ba4'; ShortName = 'Untrusted USB processes'; Warn = $true; Name = 'Block untrusted and unsigned processes that run from USB' } @{ Id = 'c0033c00-d16d-4114-a5a0-dc9b3a7d2ceb'; ShortName = 'Copied/impersonated system tools'; Warn = $true; Name = 'Block use of copied or impersonated system tools' } @{ Id = 'a8f5898e-1dc8-49a9-9878-85004b8a61e6'; ShortName = 'Webshell creation (servers)'; Warn = $true; Name = 'Block Webshell creation for Servers' } @{ Id = '92e97fa1-2edf-4476-bdd6-9dd0b4dddc7b'; ShortName = 'Win32 API calls from macros'; Warn = $true; Name = 'Block Win32 API calls from Office macros' } @{ Id = 'c1db55ab-c21a-4637-bb3f-a12568109d35'; ShortName = 'Advanced ransomware protection'; Warn = $true; Name = 'Use advanced protection against ransomware' } ) # <<< rule-catalog #region Console output function Write-AsrLine { param([string]$Text = '', [string]$Color = '') if ($Color) { Write-Host $Text -ForegroundColor $Color } else { Write-Host $Text } } function Write-AsrHeader { param([string]$Text) Write-Host '' Write-Host $Text -ForegroundColor Cyan Write-Host ('-' * [Math]::Min(78, [Math]::Max(8, $Text.Length))) -ForegroundColor DarkCyan } function Write-AsrOk { param([string]$Text) Write-Host "[ok] $Text" -ForegroundColor Green } function Write-AsrInfo { param([string]$Text) Write-Host "[info] $Text" -ForegroundColor Gray } function Write-AsrWarn { param([string]$Text) Write-Host "[warn] $Text" -ForegroundColor Yellow } function Write-AsrFail { param([string]$Text) Write-Host "[fail] $Text" -ForegroundColor Red } function Write-AsrBanner { param([string]$Subtitle) Write-Host '' Write-Host 'ASR Rules Builder' -ForegroundColor Green -NoNewline Write-Host ' by MagicSword' -ForegroundColor DarkGray -NoNewline if ($Subtitle) { Write-Host " | $Subtitle" -ForegroundColor Gray } else { Write-Host '' } } function Format-AsrCell { param([AllowNull()][object]$Value, [int]$Width) $text = if ($null -eq $Value) { '' } else { [string]$Value } if ($text.Length -gt $Width) { $text = $text.Substring(0, [Math]::Max(1, $Width - 3)) + '...' } return $text.PadRight($Width) } #endregion #region Rule catalog and mode helpers function Get-AsrRule { param([string]$Id) $key = ([string]$Id).Trim().Trim('{', '}').ToLowerInvariant() foreach ($rule in $AsrRuleCatalog) { if ($rule.Id -eq $key) { return $rule } } return $null } function Get-AsrRuleDisplayName { param([string]$Id, [switch]$Short) $rule = Get-AsrRule -Id $Id if ($null -eq $rule) { return "Unknown rule ($Id)" } if ($Short) { return $rule.ShortName } return $rule.Name } function Get-AsrRuleModeValue { param([string]$Mode) switch -CaseSensitive ($Mode) { 'off' { return 0 } 'block' { return 1 } 'audit' { return 2 } 'warn' { return 6 } } throw "Unknown ASR rule mode '$Mode'." } function Get-AsrRuleActionName { # Names of the ASRRuleActionType enum accepted by Add-MpPreference. param([int]$Value) switch ($Value) { 0 { return 'Disabled' } 1 { return 'Enabled' } 2 { return 'AuditMode' } 5 { return 'NotConfigured' } 6 { return 'Warn' } } throw "Unknown ASR rule action value $Value." } function Get-AsrRuleModeLabel { param([AllowNull()][object]$Value) if ($null -eq $Value) { return 'Not configured' } switch ([int]$Value) { 0 { return 'Off' } 1 { return 'Block' } 2 { return 'Audit' } 5 { return 'Not configured' } 6 { return 'Warn' } } return "Unknown ($Value)" } function Get-AsrCfaModeValue { param([string]$Mode) switch -CaseSensitive ($Mode) { 'off' { return 0 } 'block' { return 1 } 'audit' { return 2 } 'blockDisk' { return 3 } 'auditDisk' { return 4 } } throw "Unknown Controlled folder access mode '$Mode'." } function Get-AsrCfaActionName { param([int]$Value) switch ($Value) { 0 { return 'Disabled' } 1 { return 'Enabled' } 2 { return 'AuditMode' } 3 { return 'BlockDiskModificationOnly' } 4 { return 'AuditDiskModificationOnly' } } throw "Unknown Controlled folder access value $Value." } function Get-AsrCfaModeLabel { param([AllowNull()][object]$Value) if ($null -eq $Value) { return 'Not configured' } switch ([int]$Value) { 0 { return 'Off' } 1 { return 'Block' } 2 { return 'Audit' } 3 { return 'Block disk modification' } 4 { return 'Audit disk modification' } } return "Unknown ($Value)" } function Get-AsrNpModeValue { param([string]$Mode) switch -CaseSensitive ($Mode) { 'off' { return 0 } 'block' { return 1 } 'audit' { return 2 } } throw "Unknown Network protection mode '$Mode'." } function Get-AsrNpActionName { param([int]$Value) switch ($Value) { 0 { return 'Disabled' } 1 { return 'Enabled' } 2 { return 'AuditMode' } } throw "Unknown Network protection value $Value." } function Get-AsrNpModeLabel { param([AllowNull()][object]$Value) if ($null -eq $Value) { return 'Not configured' } switch ([int]$Value) { 0 { return 'Off' } 1 { return 'Block' } 2 { return 'Audit' } } return "Unknown ($Value)" } #endregion #region Strict JSON reader and canonical JSON writer # A small strict JSON parser (RFC 8259). Used instead of ConvertFrom-Json so that decoding # behaves the same on Windows PowerShell 5.1 and PowerShell 7 (no date coercion, keys are # case-sensitive, duplicate keys are rejected). Objects become case-sensitive # OrderedDictionary, arrays become List[object], numbers become [double]. function Skip-AsrJsonWhitespace { param([hashtable]$State) while ($State.i -lt $State.n) { $c = $State.s[$State.i] if ($c -eq [char]0x20 -or $c -eq [char]0x09 -or $c -eq [char]0x0A -or $c -eq [char]0x0D) { $State.i++ } else { break } } } function Read-AsrJsonString { param([hashtable]$State) # Caller guarantees the current character is the opening quote. $State.i++ $sb = New-Object System.Text.StringBuilder while ($true) { if ($State.i -ge $State.n) { throw 'unterminated string' } $c = $State.s[$State.i] if ($c -eq [char]'"') { $State.i++; break } if ([int]$c -lt 0x20) { throw 'control character in string' } if ($c -eq [char]'\') { if ($State.i + 1 -ge $State.n) { throw 'unterminated escape' } $e = $State.s[$State.i + 1] $State.i += 2 switch -CaseSensitive ([string]$e) { '"' { [void]$sb.Append([char]'"') } '\' { [void]$sb.Append([char]'\') } '/' { [void]$sb.Append([char]'/') } 'b' { [void]$sb.Append([char]0x08) } 'f' { [void]$sb.Append([char]0x0C) } 'n' { [void]$sb.Append([char]0x0A) } 'r' { [void]$sb.Append([char]0x0D) } 't' { [void]$sb.Append([char]0x09) } 'u' { if ($State.i + 4 -gt $State.n) { throw 'truncated \u escape' } $hex = $State.s.Substring($State.i, 4) if ($hex -notmatch '^[0-9A-Fa-f]{4}$') { throw 'invalid \u escape' } # Keep UInt16.Parse here; a Convert-based cast was flagged by Defender AMSI as a false positive. [void]$sb.Append([char][uint16]::Parse($hex, [System.Globalization.NumberStyles]::AllowHexSpecifier, [System.Globalization.CultureInfo]::InvariantCulture)) $State.i += 4 } default { throw 'invalid escape' } } continue } [void]$sb.Append($c) $State.i++ } return $sb.ToString() } function Read-AsrJsonValue { param([hashtable]$State, [int]$Depth) if ($Depth -gt 16) { throw 'nesting too deep' } Skip-AsrJsonWhitespace -State $State if ($State.i -ge $State.n) { throw 'unexpected end of JSON' } $c = $State.s[$State.i] if ($c -eq [char]'{') { $State.i++ $obj = New-Object System.Collections.Specialized.OrderedDictionary ([System.StringComparer]::Ordinal) Skip-AsrJsonWhitespace -State $State if ($State.i -lt $State.n -and $State.s[$State.i] -eq [char]'}') { $State.i++; return , $obj } while ($true) { Skip-AsrJsonWhitespace -State $State if ($State.i -ge $State.n -or $State.s[$State.i] -ne [char]'"') { throw 'expected a property name' } $key = Read-AsrJsonString -State $State Skip-AsrJsonWhitespace -State $State if ($State.i -ge $State.n -or $State.s[$State.i] -ne [char]':') { throw 'expected ":"' } $State.i++ $value = Read-AsrJsonValue -State $State -Depth ($Depth + 1) if ($obj.Contains($key)) { throw "duplicate key '$key'" } $obj.Add($key, $value) Skip-AsrJsonWhitespace -State $State if ($State.i -ge $State.n) { throw 'unterminated object' } $c = $State.s[$State.i] $State.i++ if ($c -eq [char]',') { continue } if ($c -eq [char]'}') { break } throw 'expected "," or "}"' } return , $obj } if ($c -eq [char]'[') { $State.i++ $list = New-Object 'System.Collections.Generic.List[object]' Skip-AsrJsonWhitespace -State $State if ($State.i -lt $State.n -and $State.s[$State.i] -eq [char]']') { $State.i++; return , $list } while ($true) { $item = Read-AsrJsonValue -State $State -Depth ($Depth + 1) $list.Add($item) Skip-AsrJsonWhitespace -State $State if ($State.i -ge $State.n) { throw 'unterminated array' } $c = $State.s[$State.i] $State.i++ if ($c -eq [char]',') { continue } if ($c -eq [char]']') { break } throw 'expected "," or "]"' } return , $list } if ($c -eq [char]'"') { return (Read-AsrJsonString -State $State) } foreach ($literal in @('true', 'false', 'null')) { if ($State.i + $literal.Length -le $State.n -and [string]::CompareOrdinal($State.s, $State.i, $literal, 0, $literal.Length) -eq 0) { $State.i += $literal.Length if ($literal -eq 'true') { return $true } if ($literal -eq 'false') { return $false } return $null } } $m = $State.NumberRegex.Match($State.s, $State.i) if ($m.Success -and $m.Length -gt 0) { $State.i += $m.Length return [double]::Parse($m.Value, [System.Globalization.CultureInfo]::InvariantCulture) } throw "unexpected character at position $($State.i)" } function ConvertFrom-AsrJsonText { param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Text) $state = @{ s = $Text i = 0 n = $Text.Length NumberRegex = New-Object System.Text.RegularExpressions.Regex ('\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?') } $value = Read-AsrJsonValue -State $state -Depth 0 Skip-AsrJsonWhitespace -State $state if ($state.i -ne $state.n) { throw 'unexpected characters after the JSON value' } return , $value } function ConvertTo-AsrJsonString { # Escapes like JavaScript JSON.stringify (so the encoded policy is byte-identical to the site). param([AllowEmptyString()][string]$Text) $sb = New-Object System.Text.StringBuilder [void]$sb.Append('"') for ($k = 0; $k -lt $Text.Length; $k++) { $c = $Text[$k] $code = [int]$c if ($c -eq [char]'"') { [void]$sb.Append('\"') } elseif ($c -eq [char]'\') { [void]$sb.Append('\\') } elseif ($code -eq 0x08) { [void]$sb.Append('\b') } elseif ($code -eq 0x0C) { [void]$sb.Append('\f') } elseif ($code -eq 0x0A) { [void]$sb.Append('\n') } elseif ($code -eq 0x0D) { [void]$sb.Append('\r') } elseif ($code -eq 0x09) { [void]$sb.Append('\t') } elseif ($code -lt 0x20) { [void]$sb.Append(('\u{0:x4}' -f $code)) } elseif ([char]::IsHighSurrogate($c)) { if ($k + 1 -lt $Text.Length -and [char]::IsLowSurrogate($Text[$k + 1])) { [void]$sb.Append($c); [void]$sb.Append($Text[$k + 1]); $k++ } else { [void]$sb.Append(('\u{0:x4}' -f $code)) } } elseif ([char]::IsLowSurrogate($c)) { [void]$sb.Append(('\u{0:x4}' -f $code)) } else { [void]$sb.Append($c) } } [void]$sb.Append('"') return $sb.ToString() } function ConvertTo-AsrJson { # Minimal JSON writer: IDictionary (ordered), arrays/lists, strings, numbers, bools, null. param([AllowNull()][object]$Value, [int]$Indent = 0, [int]$Level = 0) $nl = '' $pad = '' $padIn = '' $colon = ':' if ($Indent -gt 0) { $nl = "`n" $pad = ' ' * ($Indent * $Level) $padIn = ' ' * ($Indent * ($Level + 1)) $colon = ': ' } if ($null -eq $Value) { return 'null' } if ($Value -is [string]) { return (ConvertTo-AsrJsonString -Text $Value) } if ($Value -is [bool]) { if ($Value) { return 'true' } else { return 'false' } } if ($Value -is [int] -or $Value -is [long] -or $Value -is [byte] -or $Value -is [uint32] -or $Value -is [int16]) { return ([string]$Value) } if ($Value -is [double]) { if ($Value -eq [Math]::Floor($Value) -and [Math]::Abs($Value) -lt 1e15) { return ([long]$Value).ToString([System.Globalization.CultureInfo]::InvariantCulture) } return $Value.ToString('R', [System.Globalization.CultureInfo]::InvariantCulture) } if ($Value -is [System.Collections.IDictionary]) { $parts = @() foreach ($key in $Value.Keys) { $parts += $padIn + (ConvertTo-AsrJsonString -Text ([string]$key)) + $colon + (ConvertTo-AsrJson -Value $Value[$key] -Indent $Indent -Level ($Level + 1)) } if ($parts.Count -eq 0) { return '{}' } return '{' + $nl + ($parts -join (',' + $nl)) + $nl + $pad + '}' } if ($Value -is [System.Collections.IEnumerable]) { $parts = @() foreach ($item in $Value) { $parts += $padIn + (ConvertTo-AsrJson -Value $item -Indent $Indent -Level ($Level + 1)) } if ($parts.Count -eq 0) { return '[]' } return '[' + $nl + ($parts -join (',' + $nl)) + $nl + $pad + ']' } return (ConvertTo-AsrJsonString -Text ([string]$Value)) } #endregion #region Policy codec (see docs/CONTRACT.md "Policy model (v1)" and "Encoding") function Test-AsrHasControlChar { param([AllowEmptyString()][string]$Text) foreach ($c in $Text.ToCharArray()) { $code = [int]$c if ($code -le 0x1F -or ($code -ge 0x7F -and $code -le 0x9F)) { return $true } } return $false } # Unicode format characters (General Category Cf, Unicode 15.1): bidirectional overrides and # isolates, zero-width characters, the byte order mark, soft hyphen and similar invisible # characters. They can make a path or name display differently from what is applied, so the # codec rejects them. Same list as FORMAT_RANGES in site/src/lib/policy.ts. function Get-AsrUnsafeTextProblem { # Returns a description of the first unsafe character (unpaired surrogate or Unicode format # character) in $Text, or $null when there is none. param([AllowEmptyString()][string]$Text) $formatRanges = @( @(0x00AD, 0x00AD), @(0x0600, 0x0605), @(0x061C, 0x061C), @(0x06DD, 0x06DD), @(0x070F, 0x070F), @(0x0890, 0x0891), @(0x08E2, 0x08E2), @(0x180E, 0x180E), @(0x200B, 0x200F), @(0x202A, 0x202E), @(0x2060, 0x2064), @(0x2066, 0x206F), @(0xFEFF, 0xFEFF), @(0xFFF9, 0xFFFB), @(0x110BD, 0x110BD), @(0x110CD, 0x110CD), @(0x13430, 0x1343F), @(0x1BCA0, 0x1BCA3), @(0x1D173, 0x1D17A), @(0xE0001, 0xE0001), @(0xE0020, 0xE007F) ) for ($k = 0; $k -lt $Text.Length; $k++) { $c = $Text[$k] $point = [int]$c if ([char]::IsHighSurrogate($c)) { if ($k + 1 -ge $Text.Length -or -not [char]::IsLowSurrogate($Text[$k + 1])) { return 'contains an unpaired surrogate (invalid Unicode)' } $point = [char]::ConvertToUtf32($c, $Text[$k + 1]) $k++ } elseif ([char]::IsLowSurrogate($c)) { return 'contains an unpaired surrogate (invalid Unicode)' } foreach ($range in $formatRanges) { if ($point -ge $range[0] -and $point -le $range[1]) { return ('contains an invisible Unicode format character U+{0:X4} (for example a bidirectional override or zero-width character)' -f $point) } } } return $null } function Test-AsrIsJsonObject { param([AllowNull()][object]$Value) return ($Value -is [System.Collections.Specialized.OrderedDictionary]) } function Test-AsrIsJsonArray { param([AllowNull()][object]$Value) return ($Value -is [System.Collections.Generic.List[object]]) } function Assert-AsrKeys { param($Object, [string[]]$Allowed, [string]$Where) foreach ($key in $Object.Keys) { if ($Allowed -cnotcontains $key) { throw "Unknown field `"$key`" in $Where." } } } function ConvertTo-AsrEntryList { param([AllowNull()][object]$Value, [string]$Where) if (-not (Test-AsrIsJsonArray $Value)) { throw "$Where must be a list." } $out = New-Object 'System.Collections.Generic.List[string]' $index = 0 foreach ($entry in $Value) { $index++ if ($entry -isnot [string]) { throw "$Where entry $index must be text." } if ($entry.Length -lt 1) { throw "$Where entry $index is empty." } if ($entry.Length -gt 260) { throw "$Where entry $index is longer than 260 characters." } if (Test-AsrHasControlChar $entry) { throw "$Where entry $index contains a control character." } $unsafe = Get-AsrUnsafeTextProblem $entry if ($unsafe) { throw "$Where entry $index $unsafe." } $out.Add($entry) } return , $out.ToArray() } function ConvertTo-AsrPolicy { # Validates a parsed JSON tree against the v1 policy model and returns the canonical # policy as an ordered dictionary: v, name, rules, [exclusions], [ruleExclusions], [cfa], [np]. param([AllowNull()][object]$Tree) if (-not (Test-AsrIsJsonObject $Tree)) { throw 'The policy must be a JSON object.' } Assert-AsrKeys -Object $Tree -Allowed @('v', 'name', 'rules', 'exclusions', 'ruleExclusions', 'cfa', 'np') -Where 'the policy' $v = if ($Tree.Contains('v')) { $Tree['v'] } else { $null } if (-not ($v -is [double] -and $v -eq 1)) { throw "Unsupported policy version '$v'; expected 1." } $name = if ($Tree.Contains('name')) { $Tree['name'] } else { $null } if ($name -isnot [string]) { throw 'Policy name must be text.' } if (Test-AsrHasControlChar $name) { throw 'Policy name contains a control character.' } $unsafe = Get-AsrUnsafeTextProblem $name if ($unsafe) { throw "Policy name $unsafe." } $trimmed = $name.Trim() if ($trimmed.Length -lt 1) { throw 'Policy name is required.' } if ($trimmed.Length -gt 64) { throw 'Policy name must be at most 64 characters.' } $rulesIn = if ($Tree.Contains('rules')) { $Tree['rules'] } else { $null } if (-not (Test-AsrIsJsonObject $rulesIn)) { throw '"rules" must be an object of GUID -> mode.' } $rules = [ordered]@{} foreach ($id in $rulesIn.Keys) { if ($id -cnotmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { throw "Rule key `"$id`" is not a lowercase GUID." } $rule = Get-AsrRule -Id $id if ($null -eq $rule) { throw "Rule $id is not in the ASR rule catalog." } $mode = $rulesIn[$id] if ($mode -isnot [string] -or @('off', 'block', 'audit', 'warn') -cnotcontains $mode) { throw "Rule $id has unsupported mode '$mode'." } if ($mode -ceq 'warn' -and -not $rule.Warn) { throw "Rule $id ($($rule.ShortName)) does not support warn mode." } $rules[$id] = $mode } $total = 0 $policy = [ordered]@{ v = 1; name = $name; rules = $rules } if ($Tree.Contains('exclusions')) { $list = ConvertTo-AsrEntryList -Value $Tree['exclusions'] -Where 'Exclusion' $total += $list.Count if ($list.Count -gt 0) { $policy['exclusions'] = $list } } if ($Tree.Contains('ruleExclusions')) { $re = $Tree['ruleExclusions'] if (-not (Test-AsrIsJsonObject $re)) { throw '"ruleExclusions" must be an object of GUID -> list.' } $outRe = [ordered]@{} foreach ($id in $re.Keys) { if ($id -cnotmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' -or $null -eq (Get-AsrRule -Id $id)) { throw "Per-rule exclusion key $id is not a catalog rule GUID." } $list = ConvertTo-AsrEntryList -Value $re[$id] -Where "Per-rule exclusion for $id" $total += $list.Count if ($list.Count -gt 0) { $outRe[$id] = $list } } if ($outRe.Count -gt 0) { $policy['ruleExclusions'] = $outRe } } if ($Tree.Contains('cfa')) { $cfa = $Tree['cfa'] if (-not (Test-AsrIsJsonObject $cfa)) { throw '"cfa" must be an object.' } Assert-AsrKeys -Object $cfa -Allowed @('mode', 'folders', 'apps') -Where 'cfa' $mode = if ($cfa.Contains('mode')) { $cfa['mode'] } else { $null } if ($mode -isnot [string] -or @('off', 'block', 'audit', 'blockDisk', 'auditDisk') -cnotcontains $mode) { throw "Controlled folder access mode '$mode' is not supported." } $outCfa = [ordered]@{ mode = $mode } if ($cfa.Contains('folders')) { $list = ConvertTo-AsrEntryList -Value $cfa['folders'] -Where 'Protected folder' $total += $list.Count if ($list.Count -gt 0) { $outCfa['folders'] = $list } } if ($cfa.Contains('apps')) { $list = ConvertTo-AsrEntryList -Value $cfa['apps'] -Where 'Allowed application' $total += $list.Count if ($list.Count -gt 0) { $outCfa['apps'] = $list } } $policy['cfa'] = $outCfa } if ($Tree.Contains('np')) { $np = $Tree['np'] if ($np -isnot [string] -or @('off', 'block', 'audit') -cnotcontains $np) { throw "Network protection mode '$np' is not supported." } $policy['np'] = $np } if ($total -gt 300) { throw "The policy has $total exclusion/folder/app entries; the maximum is 300." } return $policy } function ConvertFrom-AsrBase64Url { param([string]$Text) if ($Text -cnotmatch '^[A-Za-z0-9_-]+$') { throw 'The policy string contains characters outside the base64url alphabet.' } if ($Text.Length % 4 -eq 1) { throw 'The policy string has an impossible base64url length.' } $b64 = $Text.Replace('-', '+').Replace('_', '/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } $bytes = [Convert]::FromBase64String($b64) # Canonical encoding leaves no stray bits in the final character. $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' $last = $alphabet.IndexOf($Text[$Text.Length - 1]) if (($Text.Length % 4 -eq 2 -and ($last -band 0x0F) -ne 0) -or ($Text.Length % 4 -eq 3 -and ($last -band 0x03) -ne 0)) { throw 'The policy string is not canonical base64url.' } return , $bytes } function ConvertTo-AsrBase64Url { param([byte[]]$Bytes) return ([Convert]::ToBase64String($Bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_') } function ConvertFrom-AsrEncodedPolicy { # Decode + strictly validate an encoded policy. Throws with a clear message on any problem. param([AllowNull()][AllowEmptyString()][string]$Encoded) if ([string]::IsNullOrEmpty($Encoded)) { throw 'The policy string is empty.' } if ($Encoded.Length -gt 8192) { throw "The policy string is $($Encoded.Length) characters; the maximum is 8192." } $bytes = ConvertFrom-AsrBase64Url -Text $Encoded try { $text = (New-Object System.Text.UTF8Encoding ($false, $true)).GetString($bytes) } catch { throw 'The policy string does not decode to valid UTF-8.' } try { $tree = ConvertFrom-AsrJsonText -Text $text } catch { throw "The policy string does not contain valid JSON ($($_.Exception.Message))." } return (ConvertTo-AsrPolicy -Tree $tree) } function ConvertTo-AsrPolicyJson { # Canonical compact JSON (contract key order) - identical to the site's JSON.stringify output. param($PolicyObject, [int]$Indent = 0) return (ConvertTo-AsrJson -Value $PolicyObject -Indent $Indent) } function ConvertTo-AsrEncodedPolicy { param($PolicyObject) $json = ConvertTo-AsrPolicyJson -PolicyObject $PolicyObject $bytes = (New-Object System.Text.UTF8Encoding ($false)).GetBytes($json) return (ConvertTo-AsrBase64Url -Bytes $bytes) } function Get-AsrPolicySlug { # Same shape as slugify() in site/src/lib/policy.ts. param([string]$Name) $s = $Name.Normalize([System.Text.NormalizationForm]::FormKD) $s = [regex]::Replace($s, '[\u0300-\u036f]', '') $s = [regex]::Replace($s.ToLowerInvariant(), '[^a-z0-9]+', '-').Trim('-') if ($s.Length -gt 48) { $s = $s.Substring(0, 48) } if ($s.Length -eq 0) { return 'asr-policy' } # Windows reserved device names cannot be used as file names (also with an extension). if ($s -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$') { return "policy-$s" } return $s } #endregion #region Environment and Defender state function Test-AsrIsWindows { return ($env:OS -eq 'Windows_NT') } function Test-AsrIsElevated { try { $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object System.Security.Principal.WindowsPrincipal ($identity) return $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) } catch { return $false } } function Test-AsrManagedByPolicy { # GPO (and the registry keys GPO/MDM write) for ASR, CFA and Network protection. $base = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender\Windows Defender Exploit Guard' $found = @() foreach ($sub in @('ASR', 'Controlled Folder Access', 'Network Protection')) { try { if (Test-Path -LiteralPath "$base\$sub") { $found += $sub } } catch { $null = $_ } } return $found } function Get-AsrRunningMode { try { $status = Get-MpComputerStatus -ErrorAction Stop if ($status.PSObject.Properties['AMRunningMode']) { return [string]$status.AMRunningMode } } catch { $null = $_ } return $null } function Test-AsrDefenderEnvironment { param([switch]$RequireElevation, [string[]]$Commands = @('Get-MpPreference'), [string]$Verb = 'This action') if (-not (Test-AsrIsWindows)) { Write-AsrFail "$Verb requires Windows with Microsoft Defender Antivirus." return $false } if ($RequireElevation -and -not (Test-AsrIsElevated)) { Write-AsrFail "$Verb needs an elevated session. Right-click PowerShell, choose 'Run as administrator', and run the command again." return $false } foreach ($cmd in $Commands) { if (-not (Get-Command -Name $cmd -ErrorAction SilentlyContinue)) { Write-AsrFail "The Microsoft Defender cmdlet $cmd is not available. Is Microsoft Defender Antivirus installed and is the Defender PowerShell module loaded?" return $false } } return $true } function Write-AsrEnvironmentWarnings { $managed = @(Test-AsrManagedByPolicy) if ($managed.Count -gt 0) { Write-AsrWarn ("Group Policy / MDM settings exist for: " + ($managed -join ', ') + '.') Write-AsrWarn 'Policy-managed settings take precedence over local settings, so local changes may not take effect.' } $mode = Get-AsrRunningMode if ($mode -and $mode -match 'Passive') { Write-AsrWarn "Microsoft Defender Antivirus is running in '$mode'. ASR rules are not enforced while Defender is passive." } elseif ($mode -and $mode -notmatch '^Normal$') { Write-AsrInfo "Microsoft Defender Antivirus running mode: $mode" } } function Get-AsrPropValue { param($Object, [string]$Name) if ($null -eq $Object) { return $null } $prop = $Object.PSObject.Properties[$Name] if ($null -eq $prop) { return $null } return $prop.Value } function ConvertTo-AsrStringList { param([AllowNull()][object]$Value) $out = New-Object 'System.Collections.Generic.List[string]' foreach ($item in @($Value)) { if ($null -ne $item -and [string]$item -ne '') { $out.Add([string]$item) } } return $out.ToArray() } function Get-AsrCurrentState { # Snapshot of the locally visible ASR / CFA / NP configuration from Get-MpPreference. $pref = Get-MpPreference $ids = @(ConvertTo-AsrStringList (Get-AsrPropValue $pref 'AttackSurfaceReductionRules_Ids')) $actions = @(@(Get-AsrPropValue $pref 'AttackSurfaceReductionRules_Actions') | Where-Object { $null -ne $_ }) $rules = [ordered]@{} for ($k = 0; $k -lt [Math]::Min($ids.Count, $actions.Count); $k++) { $id = $ids[$k].Trim().Trim('{', '}').ToLowerInvariant() $rules[$id] = [int]$actions[$k] } $readable = $true $excl = @(ConvertTo-AsrStringList (Get-AsrPropValue $pref 'AttackSurfaceReductionOnlyExclusions')) $folders = @(ConvertTo-AsrStringList (Get-AsrPropValue $pref 'ControlledFolderAccessProtectedFolders')) $apps = @(ConvertTo-AsrStringList (Get-AsrPropValue $pref 'ControlledFolderAccessAllowedApplications')) foreach ($list in @($excl, $folders, $apps)) { if (@($list | Where-Object { $_ -like 'N/A*' }).Count -gt 0) { $readable = $false } } if (-not $readable) { $excl = @($excl | Where-Object { $_ -notlike 'N/A*' }) $folders = @($folders | Where-Object { $_ -notlike 'N/A*' }) $apps = @($apps | Where-Object { $_ -notlike 'N/A*' }) } # Per-rule exclusions (Defender platform builds that expose them): one entry per rule, the # rule's paths joined with '|' (the registry stores them joined with '>'). $ruleExclKnown = ($null -ne $pref -and $null -ne $pref.PSObject.Properties['AttackSurfaceReductionRules_RuleSpecificExclusions_Id']) $ruleExcl = [ordered]@{} if ($ruleExclKnown) { $reIds = @(Get-AsrPropValue $pref 'AttackSurfaceReductionRules_RuleSpecificExclusions_Id') $reVals = @(Get-AsrPropValue $pref 'AttackSurfaceReductionRules_RuleSpecificExclusions') for ($k = 0; $k -lt [Math]::Min($reIds.Count, $reVals.Count); $k++) { if ($null -eq $reIds[$k] -or [string]$reIds[$k] -eq '') { continue } if ([string]$reIds[$k] -like 'N/A*' -or [string]$reVals[$k] -like 'N/A*') { $readable = $false; continue } $id = ([string]$reIds[$k]).Trim().Trim('{', '}').ToLowerInvariant() $paths = @(([string]$reVals[$k]).Split([char[]]@('|', '>'), [System.StringSplitOptions]::RemoveEmptyEntries)) if ($paths.Count -gt 0) { $ruleExcl[$id] = [string[]]$paths } } } $cfa = Get-AsrPropValue $pref 'EnableControlledFolderAccess' $np = Get-AsrPropValue $pref 'EnableNetworkProtection' return [pscustomobject]@{ Rules = $rules AsrOnlyExclusions = [string[]]$excl RuleExclusions = $ruleExcl RuleExclusionsKnown = $ruleExclKnown CfaMode = $(if ($null -ne $cfa) { [int]$cfa } else { $null }) CfaFolders = [string[]]$folders CfaApps = [string[]]$apps NpMode = $(if ($null -ne $np) { [int]$np } else { $null }) ExclusionsReadable = $readable } } function Test-AsrRuleExclusionPresent { # Pure: is $Path listed for rule $Id in a state's RuleExclusions map? param($State, [string]$Id, [string]$Path) if ($null -eq $State -or -not $State.PSObject.Properties['RuleExclusions'] -or $null -eq $State.RuleExclusions) { return $false } if (-not $State.RuleExclusions.Contains($Id)) { return $false } return (Test-AsrListContains $State.RuleExclusions[$Id] $Path) } function Test-AsrRuleExclusionSupport { # Per-rule exclusions are only documented for GPO/Intune. Some Defender platform builds expose # undocumented Add-MpPreference parameters for them; feature-detect, never assume. $cmd = Get-Command -Name Add-MpPreference -ErrorAction SilentlyContinue if ($null -eq $cmd) { return $false } return ($cmd.Parameters.ContainsKey('AttackSurfaceReductionRules_RuleSpecificExclusions_Id') -and $cmd.Parameters.ContainsKey('AttackSurfaceReductionRules_RuleSpecificExclusions')) } function Test-AsrListContains { param([string[]]$List, [string]$Item) foreach ($x in @($List)) { if ([string]::Equals($x, $Item, [System.StringComparison]::OrdinalIgnoreCase)) { return $true } } return $false } #endregion #region Install function New-AsrInstallPlan { # Pure: compares a policy with a state snapshot and returns plan rows. param($PolicyObject, $State, [bool]$RuleExclusionSupport) $rows = New-Object 'System.Collections.Generic.List[object]' foreach ($id in $PolicyObject['rules'].Keys) { $newValue = Get-AsrRuleModeValue $PolicyObject['rules'][$id] $current = if ($State.Rules.Contains($id)) { $State.Rules[$id] } else { $null } $rows.Add([pscustomobject]@{ Kind = 'Rule'; Key = $id; Label = (Get-AsrRuleDisplayName -Id $id -Short) Current = (Get-AsrRuleModeLabel $current); New = (Get-AsrRuleModeLabel $newValue) Change = ($null -eq $current -or [int]$current -ne $newValue); Note = '' }) } if ($PolicyObject.Contains('exclusions')) { foreach ($path in $PolicyObject['exclusions']) { $present = Test-AsrListContains $State.AsrOnlyExclusions $path $rows.Add([pscustomobject]@{ Kind = 'Exclusion'; Key = $path; Label = "ASR exclusion: $path"; Path = $path Current = $(if ($present) { 'Present' } elseif ($State.ExclusionsReadable) { 'Absent' } else { 'Unknown' }) New = 'Present'; Change = (-not $present); Note = '' }) } } if ($PolicyObject.Contains('ruleExclusions')) { foreach ($id in $PolicyObject['ruleExclusions'].Keys) { foreach ($path in $PolicyObject['ruleExclusions'][$id]) { $note = if ($RuleExclusionSupport) { 'Undocumented Add-MpPreference parameter; verified with Get-MpPreference' } else { 'Not applied: configure per-rule exclusions via Intune or Group Policy' } $known = ($RuleExclusionSupport -and $State.PSObject.Properties['RuleExclusionsKnown'] -and $State.RuleExclusionsKnown) $present = ($known -and (Test-AsrRuleExclusionPresent -State $State -Id $id -Path $path)) $rows.Add([pscustomobject]@{ Kind = 'RuleExclusion'; Key = "$id|$path"; Label = ((Get-AsrRuleDisplayName -Id $id -Short) + " exclusion: $path"); Path = $path Current = $(if ($present) { 'Present' } elseif ($known -and $State.ExclusionsReadable) { 'Absent' } else { 'Unknown' }) New = $(if ($RuleExclusionSupport) { 'Present' } else { 'Not applied' }) Change = ($RuleExclusionSupport -and -not $present); Note = $note }) } } } if ($PolicyObject.Contains('cfa')) { $cfa = $PolicyObject['cfa'] $newValue = Get-AsrCfaModeValue $cfa['mode'] $rows.Add([pscustomobject]@{ Kind = 'CfaMode'; Key = 'cfa'; Label = 'Controlled folder access' Current = (Get-AsrCfaModeLabel $State.CfaMode); New = (Get-AsrCfaModeLabel $newValue) Change = ($null -eq $State.CfaMode -or [int]$State.CfaMode -ne $newValue); Note = '' }) foreach ($pair in @(@('folders', 'CfaFolder', 'Protected folder', 'CfaFolders'), @('apps', 'CfaApp', 'Allowed app', 'CfaApps'))) { if ($cfa.Contains($pair[0])) { foreach ($path in $cfa[$pair[0]]) { $present = Test-AsrListContains $State.($pair[3]) $path $rows.Add([pscustomobject]@{ Kind = $pair[1]; Key = $path; Label = "$($pair[2]): $path"; Path = $path Current = $(if ($present) { 'Present' } elseif ($State.ExclusionsReadable) { 'Absent' } else { 'Unknown' }) New = 'Present'; Change = (-not $present); Note = '' }) } } } } if ($PolicyObject.Contains('np')) { $newValue = Get-AsrNpModeValue $PolicyObject['np'] $rows.Add([pscustomobject]@{ Kind = 'NetworkProtection'; Key = 'np'; Label = 'Network protection' Current = (Get-AsrNpModeLabel $State.NpMode); New = (Get-AsrNpModeLabel $newValue) Change = ($null -eq $State.NpMode -or [int]$State.NpMode -ne $newValue); Note = '' }) } return $rows.ToArray() } function Test-AsrBroadPath { # Pure: does an exclusion / allowed-app path cover a very large or user-writable part of the # disk (a leading wildcard, a drive root, or a broad folder such as C:\Users or %TEMP%)? param([string]$Path) $p = $Path.Trim() if ($p.StartsWith('*') -or $p.StartsWith('?')) { return $true } $base = $p do { $before = $base $base = [regex]::Replace($base, '(\\|/)+$', '') $base = [regex]::Replace($base, '(\\|/)\*(\.\*)?$', '') } while ($base -ne $before) if ($base -eq '' -or $base -eq '*') { return $true } $base = [regex]::Replace($base, '^[A-Za-z]:', 'C:') $broad = @( 'C:', 'C:\Users', 'C:\Users\Public', 'C:\ProgramData', 'C:\Windows', 'C:\Windows\Temp', 'C:\Temp', 'C:\Program Files', 'C:\Program Files (x86)', '%SystemDrive%', '%SystemRoot%', '%windir%', '%USERPROFILE%', '%TEMP%', '%TMP%', '%APPDATA%', '%LOCALAPPDATA%', '%ProgramData%', '%ALLUSERSPROFILE%', '%PUBLIC%', '%ProgramFiles%', '%ProgramFiles(x86)%', '%HOMEDRIVE%', '%HOMEPATH%' ) foreach ($b in $broad) { if ([string]::Equals($base, $b, [System.StringComparison]::OrdinalIgnoreCase)) { return $true } } return $false } function Get-AsrBroadPathWarnings { # Pure: warnings for very broad exclusions and allowed apps in a policy. param($PolicyObject) $out = @() $check = @() if ($PolicyObject.Contains('exclusions')) { foreach ($x in $PolicyObject['exclusions']) { $check += , @('ASR exclusion', $x) } } if ($PolicyObject.Contains('ruleExclusions')) { foreach ($id in $PolicyObject['ruleExclusions'].Keys) { foreach ($x in $PolicyObject['ruleExclusions'][$id]) { $check += , @(((Get-AsrRuleDisplayName -Id $id -Short) + ' exclusion'), $x) } } } if ($PolicyObject.Contains('cfa') -and $PolicyObject['cfa'].Contains('apps')) { foreach ($x in $PolicyObject['cfa']['apps']) { $check += , @('Controlled folder access allowed app', $x) } } foreach ($c in $check) { if (Test-AsrBroadPath $c[1]) { $out += "Very broad $($c[0]): '$($c[1])'. It turns protection off for a large or user-writable part of the disk. Prefer specific signed binaries." } } return $out } function Write-AsrPlan { param([object[]]$Plan, [string]$Title = 'Plan', [string]$Footer = 'Rules not in the policy are left untouched.') Write-AsrHeader $Title if (@($Plan).Count -eq 0) { Write-AsrInfo 'Nothing to change.'; return } Write-Host ((Format-AsrCell 'Setting' 46) + ' ' + (Format-AsrCell 'Current' 16) + ' ' + (Format-AsrCell 'New' 16)) -ForegroundColor DarkGray foreach ($row in $Plan) { $color = if ($row.Note -like 'Not applied*') { 'Yellow' } elseif ($row.Change) { 'White' } else { 'DarkGray' } $marker = if ($row.Change) { '*' } else { ' ' } # Paths are never truncated: the setting name goes in the table and the full path on its # own line, so what is approved is exactly what is shown. $title = $row.Label $path = $null if ($row.PSObject.Properties['Path'] -and $row.Path) { $path = [string]$row.Path if ($title.EndsWith(': ' + $path)) { $title = $title.Substring(0, $title.Length - $path.Length - 2) } } Write-Host ((Format-AsrCell $title 46) + ' ' + (Format-AsrCell $row.Current 16) + ' ' + (Format-AsrCell $row.New 16) + " $marker") -ForegroundColor $color if ($null -ne $path) { Write-Host " path: $path" -ForegroundColor $color } if ($row.Note) { Write-Host " $($row.Note)" -ForegroundColor Yellow } } $changes = @($Plan | Where-Object { $_.Change }).Count Write-Host '' Write-AsrInfo "$changes of $(@($Plan).Count) settings will change (marked *). $Footer" } function Read-AsrConfirmation { param([string]$Prompt) Write-Host "$Prompt " -ForegroundColor Cyan -NoNewline try { $answer = Read-Host } catch { # -NonInteractive sessions, SYSTEM services and redirected input cannot prompt. Write-Host '' Write-AsrFail 'No interactive console: rerun with -Force to confirm non-interactively.' return $false } if ($null -eq $answer) { return $false } return ([string]$answer).Trim() -match '^(?i:y|yes)$' } #endregion #region Backup folder security # Backups decide what Restore applies, so they must only ever come from administrators. # $env:ProgramData lets standard users create files and folders (CREATOR OWNER gets full control # of what they create), so the ASR-Rules-Builder and backups folders get their own access list: # SYSTEM and Administrators only, inheritance from ProgramData disabled. function Get-AsrBackupRoot { $root = $env:ProgramData if ([string]::IsNullOrEmpty($root)) { $root = [Environment]::GetFolderPath('CommonApplicationData') } return (Join-Path $root 'ASR-Rules-Builder') } function Get-AsrBackupDirectory { return (Join-Path (Get-AsrBackupRoot) 'backups') } function Test-AsrAclSupported { # Windows access lists are enforced only on Windows. The test harness on macOS/Linux replaces # this probe (and the ACL helpers below) to exercise the decision logic. return ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) } function Test-AsrTrustedSid { param([AllowNull()][string]$Sid) $trusted = @( 'S-1-5-18' # NT AUTHORITY\SYSTEM 'S-1-5-32-544' # BUILTIN\Administrators 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464' # NT SERVICE\TrustedInstaller ) return ($null -ne $Sid -and $trusted -contains $Sid) } function Get-AsrPathSecurity { # Owner, reparse-point flag and access rules (as SIDs) of a file or folder. param([string]$Path) $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue if ($null -eq $item) { return [pscustomobject]@{ Exists = $false; IsDirectory = $false; IsReparsePoint = $false; OwnerSid = $null; Rules = @() } } $acl = Get-Acl -LiteralPath $Path $rules = @(foreach ($r in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) { [pscustomobject]@{ Sid = [string]$r.IdentityReference.Value Allow = ($r.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) Rights = [int]$r.FileSystemRights InheritOnly = [bool]($r.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) } }) $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]) return [pscustomobject]@{ Exists = $true IsDirectory = [bool]$item.PSIsContainer IsReparsePoint = [bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) OwnerSid = $(if ($null -ne $owner) { [string]$owner.Value } else { $null }) Rules = $rules } } function New-AsrProtectedSecurity { param([switch]$Directory) if ($Directory) { $sec = New-Object System.Security.AccessControl.DirectorySecurity $inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' } else { $sec = New-Object System.Security.AccessControl.FileSecurity $inherit = [System.Security.AccessControl.InheritanceFlags]::None } $sec.SetAccessRuleProtection($true, $false) foreach ($sid in @('S-1-5-18', 'S-1-5-32-544')) { $id = New-Object System.Security.Principal.SecurityIdentifier ($sid) $sec.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule ($id, [System.Security.AccessControl.FileSystemRights]::FullControl, $inherit, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow))) } return $sec } function Set-AsrProtectedAcl { # SYSTEM + Administrators full control, inheritance disabled, owner Administrators. param([string]$Path, [switch]$Directory) $sec = New-AsrProtectedSecurity -Directory:$Directory $withOwner = New-AsrProtectedSecurity -Directory:$Directory $withOwner.SetOwner((New-Object System.Security.Principal.SecurityIdentifier ('S-1-5-32-544'))) try { Set-Acl -LiteralPath $Path -AclObject $withOwner -ErrorAction Stop } catch { Set-Acl -LiteralPath $Path -AclObject $sec -ErrorAction Stop } } function New-AsrProtectedDirectory { # Creates one folder with the protected access list from the start (no window in which it # inherits the ProgramData access list), then sets the owner to Administrators. param([string]$Path) $sec = New-AsrProtectedSecurity -Directory $created = $false try { if ($PSVersionTable.PSEdition -eq 'Core') { [void][System.IO.FileSystemAclExtensions]::Create((New-Object System.IO.DirectoryInfo ($Path)), $sec) } else { [void][System.IO.Directory]::CreateDirectory($Path, $sec) } $created = $true } catch { $created = $false } if (-not $created) { [void][System.IO.Directory]::CreateDirectory($Path) } Set-AsrProtectedAcl -Path $Path -Directory } function Get-AsrUntrustedRights { # Pure: "SID (rights)" texts for allow rules that give an untrusted principal any of $Mask. param($Info, [int]$Mask, [switch]$IncludeInheritOnly) $out = @() foreach ($r in @($Info.Rules)) { if (-not $r.Allow) { continue } if ($r.InheritOnly -and -not $IncludeInheritOnly) { continue } if (Test-AsrTrustedSid $r.Sid) { continue } if (($r.Rights -band $Mask) -ne 0) { $out += ('{0} (0x{1:X})' -f $r.Sid, $r.Rights) } } return $out } function Test-AsrBackupFolderState { # Pure: classify a folder's security info. Fatal = refuse (cannot be repaired safely); # NeedsRepair = owner is fine but the access list grants something to non-administrators. param($Info, [string]$Path) if (-not $Info.Exists) { return [pscustomobject]@{ Fatal = $null; NeedsRepair = $false; Missing = $true; Reason = '' } } $fatal = $null if (-not $Info.IsDirectory) { $fatal = "$Path exists but is not a folder." } elseif ($Info.IsReparsePoint) { $fatal = "$Path is a symbolic link or junction." } elseif (-not (Test-AsrTrustedSid $Info.OwnerSid)) { $fatal = "$Path is owned by $($Info.OwnerSid), not by Administrators or SYSTEM." } $loose = @(Get-AsrUntrustedRights -Info $Info -Mask -1 -IncludeInheritOnly) return [pscustomobject]@{ Fatal = $fatal NeedsRepair = ($loose.Count -gt 0) Missing = $false Reason = $(if ($loose.Count -gt 0) { 'grants access to ' + ($loose -join ', ') } else { '' }) } } function Initialize-AsrBackupDirectory { # Returns the backups folder after making sure ASR-Rules-Builder and backups are real folders owned by # Administrators/SYSTEM with the protected access list. Throws when a folder cannot be trusted. # -ReadOnly (Restore -WhatIf): never creates or repairs; reports what it would repair. param([switch]$ReadOnly) $root = Get-AsrBackupRoot $dir = Get-AsrBackupDirectory if (-not (Test-AsrAclSupported)) { if (-not $ReadOnly) { [void][System.IO.Directory]::CreateDirectory($dir) } return $dir } foreach ($p in @($root, $dir)) { $state = Test-AsrBackupFolderState -Info (Get-AsrPathSecurity -Path $p) -Path $p if ($state.Missing) { if ($ReadOnly) { return $dir } New-AsrProtectedDirectory -Path $p $state = Test-AsrBackupFolderState -Info (Get-AsrPathSecurity -Path $p) -Path $p } if ($state.Fatal) { throw "Unsafe backup folder: $($state.Fatal) A standard user may have created it to plant backups. Inspect it, delete it (Remove-Item -LiteralPath '$p' -Recurse -Force) and run the command again." } if ($state.NeedsRepair) { if ($ReadOnly) { Write-AsrWarn "What if: the access list of $p would be reset to SYSTEM and Administrators only (it $($state.Reason))."; continue } Set-AsrProtectedAcl -Path $p -Directory $state = Test-AsrBackupFolderState -Info (Get-AsrPathSecurity -Path $p) -Path $p if ($state.Fatal -or $state.NeedsRepair) { throw "Could not restrict the access list of ${p}: it still $($state.Reason)." } Write-AsrInfo "Restricted the access list of $p to SYSTEM and Administrators." } } return $dir } function Get-AsrBackupTrustProblem { # Why a backup file must not be trusted, or $null. A trusted backup is a regular file owned by # Administrators/SYSTEM that only administrators can change, in a folder (not a link) where # only administrators can replace files. param([string]$Path) if (-not (Test-AsrAclSupported)) { return $null } $info = Get-AsrPathSecurity -Path $Path if (-not $info.Exists) { return 'the file does not exist' } if ($info.IsDirectory) { return 'it is a folder' } if ($info.IsReparsePoint) { return 'it is a symbolic link or other reparse point' } if (-not (Test-AsrTrustedSid $info.OwnerSid)) { return "it is owned by $($info.OwnerSid), not by Administrators or SYSTEM" } # Rights that let a principal change the file: WriteData, AppendData, WriteExtendedAttributes, # WriteAttributes, Delete, ChangePermissions, TakeOwnership, GENERIC_ALL, GENERIC_WRITE. $writeMask = 0x2 -bor 0x4 -bor 0x10 -bor 0x100 -bor 0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000 -bor 0x40000000 # Rights on the folder that let a principal replace or re-permission a file inside it: # DeleteSubdirectoriesAndFiles, ChangePermissions, TakeOwnership, GENERIC_ALL. $replaceMask = 0x40 -bor 0x40000 -bor 0x80000 -bor 0x10000000 $w = @(Get-AsrUntrustedRights -Info $info -Mask $writeMask) if ($w.Count -gt 0) { return "non-administrators can change it: $($w -join ', ')" } $parent = Split-Path -Parent $Path $pinfo = Get-AsrPathSecurity -Path $parent if ($pinfo.IsReparsePoint) { return "its folder $parent is a symbolic link or junction" } if (-not (Test-AsrTrustedSid $pinfo.OwnerSid)) { return "its folder $parent is owned by $($pinfo.OwnerSid), who could replace it" } $d = @(Get-AsrUntrustedRights -Info $pinfo -Mask $replaceMask) if ($d.Count -gt 0) { return "non-administrators can replace files in its folder ${parent}: $($d -join ', ')" } return $null } function Read-AsrTrustedBackupText { # Opens the file (deny write/delete while open), checks it can be trusted, then reads it. param([string]$Path) $stream = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read) try { $problem = Get-AsrBackupTrustProblem -Path $Path if ($problem) { throw "Untrusted backup ${Path}: $problem. Only backups written by an administrator are restored; copy a trusted backup into $(Get-AsrBackupDirectory)." } if ($stream.Length -gt 1MB) { throw 'The backup file is larger than 1 MB.' } $reader = New-Object System.IO.StreamReader ($stream, (New-Object System.Text.UTF8Encoding ($false)), $true) return $reader.ReadToEnd() } finally { $stream.Dispose() } } function ConvertTo-AsrBackupObject { param($State) $rules = @() foreach ($id in $State.Rules.Keys) { $rules += [ordered]@{ id = $id; action = [int]$State.Rules[$id] } } return [ordered]@{ tool = 'ASR Rules Builder' schema = 1 created = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [System.Globalization.CultureInfo]::InvariantCulture) computer = [Environment]::MachineName exclusionsReadable = [bool]$State.ExclusionsReadable rules = $rules asrOnlyExclusions = @($State.AsrOnlyExclusions) ruleExclusions = $(if ($State.PSObject.Properties['RuleExclusionsKnown'] -and $State.RuleExclusionsKnown) { $re = [ordered]@{}; foreach ($id in $State.RuleExclusions.Keys) { $re[$id] = @($State.RuleExclusions[$id]) }; $re } else { $null }) cfa = $(if ($null -ne $State.CfaMode) { [ordered]@{ mode = [int]$State.CfaMode; folders = @($State.CfaFolders); apps = @($State.CfaApps) } } else { $null }) np = $(if ($null -ne $State.NpMode) { [int]$State.NpMode } else { $null }) } } function Save-AsrBackup { param($State) $dir = Initialize-AsrBackupDirectory $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss', [System.Globalization.CultureInfo]::InvariantCulture) $path = Join-Path $dir "asr-backup-$stamp.json" $n = 1 while (Test-Path -LiteralPath $path) { $path = Join-Path $dir "asr-backup-$stamp-$n.json"; $n++ } $json = ConvertTo-AsrJson -Value (ConvertTo-AsrBackupObject -State $State) -Indent 2 $bytes = (New-Object System.Text.UTF8Encoding ($false)).GetBytes($json + "`n") # CreateNew: never write into (or through) a file that already exists. $stream = [System.IO.File]::Open($path, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None) try { $stream.Write($bytes, 0, $bytes.Length) } finally { $stream.Dispose() } if (Test-AsrAclSupported) { Set-AsrProtectedAcl -Path $path } return $path } #endregion #region Install (apply) function Invoke-AsrApplyPolicy { # Applies the policy. Returns a list of error messages (empty on success). param($PolicyObject, [bool]$RuleExclusionSupport, $State) $errors = New-Object 'System.Collections.Generic.List[string]' $ids = @($PolicyObject['rules'].Keys) if ($ids.Count -gt 0) { $actions = @($ids | ForEach-Object { Get-AsrRuleActionName (Get-AsrRuleModeValue $PolicyObject['rules'][$_]) }) try { Add-MpPreference -AttackSurfaceReductionRules_Ids $ids -AttackSurfaceReductionRules_Actions $actions -ErrorAction Stop } catch { $errors.Add("ASR rules: $($_.Exception.Message)") } } if ($PolicyObject.Contains('exclusions')) { try { Add-MpPreference -AttackSurfaceReductionOnlyExclusions ([string[]]$PolicyObject['exclusions']) -ErrorAction Stop } catch { $errors.Add("ASR-only exclusions: $($_.Exception.Message)") } } if ($PolicyObject.Contains('ruleExclusions') -and $RuleExclusionSupport) { $reIds = @(); $rePaths = @() foreach ($id in $PolicyObject['ruleExclusions'].Keys) { foreach ($path in $PolicyObject['ruleExclusions'][$id]) { # Add-MpPreference appends to a rule's list; skip paths that are already there. if (Test-AsrRuleExclusionPresent -State $State -Id $id -Path $path) { continue } $reIds += $id; $rePaths += $path } } if ($reIds.Count -gt 0) { try { $splat = @{ AttackSurfaceReductionRules_RuleSpecificExclusions_Id = [string[]]$reIds AttackSurfaceReductionRules_RuleSpecificExclusions = [string[]]$rePaths ErrorAction = 'Stop' } Add-MpPreference @splat } catch { $errors.Add("Per-rule exclusions: $($_.Exception.Message)") } } } if ($PolicyObject.Contains('cfa')) { $cfa = $PolicyObject['cfa'] if ($cfa.Contains('folders')) { try { Add-MpPreference -ControlledFolderAccessProtectedFolders ([string[]]$cfa['folders']) -ErrorAction Stop } catch { $errors.Add("Controlled folder access protected folders: $($_.Exception.Message)") } } if ($cfa.Contains('apps')) { try { Add-MpPreference -ControlledFolderAccessAllowedApplications ([string[]]$cfa['apps']) -ErrorAction Stop } catch { $errors.Add("Controlled folder access allowed apps: $($_.Exception.Message)") } } try { Set-MpPreference -EnableControlledFolderAccess (Get-AsrCfaActionName (Get-AsrCfaModeValue $cfa['mode'])) -ErrorAction Stop } catch { $errors.Add("Controlled folder access mode: $($_.Exception.Message)") } } if ($PolicyObject.Contains('np')) { try { Set-MpPreference -EnableNetworkProtection (Get-AsrNpActionName (Get-AsrNpModeValue $PolicyObject['np'])) -ErrorAction Stop } catch { $errors.Add("Network protection: $($_.Exception.Message)") } } return $errors.ToArray() } function Test-AsrPolicyApplied { # Pure: compares a policy with a state snapshot taken after applying. Returns mismatch rows. param($PolicyObject, $State, [bool]$RuleExclusionSupport = $false) $out = New-Object 'System.Collections.Generic.List[object]' foreach ($id in $PolicyObject['rules'].Keys) { $want = Get-AsrRuleModeValue $PolicyObject['rules'][$id] $have = if ($State.Rules.Contains($id)) { $State.Rules[$id] } else { $null } $ok = ($null -ne $have -and [int]$have -eq $want) $out.Add([pscustomobject]@{ Label = (Get-AsrRuleDisplayName -Id $id -Short); Expected = (Get-AsrRuleModeLabel $want); Actual = (Get-AsrRuleModeLabel $have); Ok = $ok }) } $lists = @() if ($PolicyObject.Contains('exclusions')) { $lists += , @('ASR exclusion', $PolicyObject['exclusions'], $State.AsrOnlyExclusions) } if ($PolicyObject.Contains('cfa')) { $cfa = $PolicyObject['cfa'] $want = Get-AsrCfaModeValue $cfa['mode'] $out.Add([pscustomobject]@{ Label = 'Controlled folder access'; Expected = (Get-AsrCfaModeLabel $want); Actual = (Get-AsrCfaModeLabel $State.CfaMode); Ok = ($null -ne $State.CfaMode -and [int]$State.CfaMode -eq $want) }) if ($cfa.Contains('folders')) { $lists += , @('Protected folder', $cfa['folders'], $State.CfaFolders) } if ($cfa.Contains('apps')) { $lists += , @('Allowed app', $cfa['apps'], $State.CfaApps) } } foreach ($l in $lists) { foreach ($path in $l[1]) { $present = Test-AsrListContains $l[2] $path $out.Add([pscustomobject]@{ Label = "$($l[0]): $path"; Expected = 'Present'; Actual = $(if ($present) { 'Present' } elseif ($State.ExclusionsReadable) { 'Absent' } else { 'Unreadable' }); Ok = $present }) } } if ($RuleExclusionSupport -and $PolicyObject.Contains('ruleExclusions') -and $State.PSObject.Properties['RuleExclusionsKnown'] -and $State.RuleExclusionsKnown) { foreach ($id in $PolicyObject['ruleExclusions'].Keys) { foreach ($path in $PolicyObject['ruleExclusions'][$id]) { $present = Test-AsrRuleExclusionPresent -State $State -Id $id -Path $path $out.Add([pscustomobject]@{ Label = ((Get-AsrRuleDisplayName -Id $id -Short) + " exclusion: $path"); Expected = 'Present'; Actual = $(if ($present) { 'Present' } elseif ($State.ExclusionsReadable) { 'Absent' } else { 'Unreadable' }); Ok = $present }) } } } if ($PolicyObject.Contains('np')) { $want = Get-AsrNpModeValue $PolicyObject['np'] $out.Add([pscustomobject]@{ Label = 'Network protection'; Expected = (Get-AsrNpModeLabel $want); Actual = (Get-AsrNpModeLabel $State.NpMode); Ok = ($null -ne $State.NpMode -and [int]$State.NpMode -eq $want) }) } return $out.ToArray() } function Write-AsrVerification { param([object[]]$Rows) Write-AsrHeader 'Verification (re-read with Get-MpPreference)' foreach ($row in $Rows) { if ($row.Ok) { Write-AsrOk "$($row.Label): $($row.Actual)" } else { Write-AsrFail "$($row.Label): expected $($row.Expected), found $($row.Actual)" } } } function Invoke-AsrInstall { # Install a validated policy object. Returns the contract exit code. param($PolicyObject, [switch]$Force, [switch]$WhatIfMode) Write-AsrBanner -Subtitle "Install: $($PolicyObject['name'])" if (-not (Test-AsrDefenderEnvironment -RequireElevation -Commands @('Get-MpPreference', 'Add-MpPreference', 'Set-MpPreference') -Verb 'Install')) { return 2 } Write-AsrEnvironmentWarnings try { $state = Get-AsrCurrentState } catch { Write-AsrFail "Could not read the current Defender configuration: $($_.Exception.Message)"; return 2 } $ruleExclusionSupport = Test-AsrRuleExclusionSupport $plan = @(New-AsrInstallPlan -PolicyObject $PolicyObject -State $state -RuleExclusionSupport $ruleExclusionSupport) Write-AsrPlan -Plan $plan -Title "Plan for '$($PolicyObject['name'])'" $omitted = @($plan | Where-Object { $_.New -eq 'Not applied' }) if (@($plan | Where-Object { $_.Kind -eq 'RuleExclusion' -and -not $ruleExclusionSupport }).Count -gt 0) { Write-AsrWarn 'This Defender version has no cmdlet support for per-rule exclusions. Configure them with Intune (endpoint security ASR policy) or Group Policy.' } foreach ($w in @(Get-AsrBroadPathWarnings -PolicyObject $PolicyObject)) { Write-AsrWarn $w } if ($WhatIfMode) { Write-AsrInfo 'What if: no changes were made.' return 0 } if (-not $Force) { if (-not (Read-AsrConfirmation 'Are you sure you want to install this ASR policy? [y/N]')) { Write-AsrWarn 'Cancelled. Nothing was changed.' return 4 } } try { $backup = Save-AsrBackup -State $state Write-AsrOk "Backup of the current settings: $backup" } catch { Write-AsrFail "Could not write the backup, so nothing was changed: $($_.Exception.Message)" return 2 } $errors = @(Invoke-AsrApplyPolicy -PolicyObject $PolicyObject -RuleExclusionSupport $ruleExclusionSupport -State $state) foreach ($e in $errors) { Write-AsrFail $e } try { $after = Get-AsrCurrentState } catch { Write-AsrFail "Could not re-read the Defender configuration: $($_.Exception.Message)"; return 3 } $verify = @(Test-AsrPolicyApplied -PolicyObject $PolicyObject -State $after -RuleExclusionSupport $ruleExclusionSupport) Write-AsrVerification -Rows $verify $bad = @($verify | Where-Object { -not $_.Ok }).Count Write-Host '' if ($errors.Count -gt 0 -or $bad -gt 0) { Write-AsrFail "Install finished with $($errors.Count) error(s) and $bad verification mismatch(es)." Write-AsrInfo "To roll back, run this script with -Action Restore -BackupPath '$backup'." return 3 } if ($omitted.Count -gt 0) { Write-AsrWarn "Policy '$($PolicyObject['name'])' installed and verified, but $($omitted.Count) setting(s) could not be applied on this device (marked 'Not applied' in the plan). Exit code 5." return 5 } Write-AsrOk "Policy '$($PolicyObject['name'])' installed and verified." Write-AsrInfo 'Next: watch events with -Action Collect, then promote audit rules with zero hits to block.' return 0 } #endregion #region Save function ConvertTo-AsrPsLiteral { # Single-quoted PowerShell literal. PowerShell also treats the typographic quotes # U+2018..U+201B as single quotes, so every quote character is doubled. param([AllowEmptyString()][string]$Text) $escaped = [regex]::Replace($Text, "['\u2018\u2019\u201A\u201B]", '$0$0') return "'" + $escaped + "'" } function ConvertTo-AsrPsPolicyLiteral { # PowerShell source text that rebuilds the validated policy object (data only, no code). param($PolicyObject) $lines = New-Object 'System.Collections.Generic.List[string]' $lines.Add('$AsrPolicy = [ordered]@{') $lines.Add(' v = 1') $lines.Add(' name = ' + (ConvertTo-AsrPsLiteral $PolicyObject['name'])) $lines.Add(' rules = [ordered]@{') foreach ($id in $PolicyObject['rules'].Keys) { $lines.Add(' ' + (ConvertTo-AsrPsLiteral $id) + ' = ' + (ConvertTo-AsrPsLiteral $PolicyObject['rules'][$id]) + ' # ' + (Get-AsrRuleDisplayName -Id $id -Short)) } $lines.Add(' }') $listLiteral = { param($items) return '[string[]]@(' + ((@($items) | ForEach-Object { ConvertTo-AsrPsLiteral $_ }) -join ', ') + ')' } if ($PolicyObject.Contains('exclusions')) { $lines.Add(' exclusions = ' + (& $listLiteral $PolicyObject['exclusions'])) } if ($PolicyObject.Contains('ruleExclusions')) { $lines.Add(' ruleExclusions = [ordered]@{') foreach ($id in $PolicyObject['ruleExclusions'].Keys) { $lines.Add(' ' + (ConvertTo-AsrPsLiteral $id) + ' = ' + (& $listLiteral $PolicyObject['ruleExclusions'][$id])) } $lines.Add(' }') } if ($PolicyObject.Contains('cfa')) { $cfa = $PolicyObject['cfa'] $lines.Add(' cfa = [ordered]@{') $lines.Add(' mode = ' + (ConvertTo-AsrPsLiteral $cfa['mode'])) if ($cfa.Contains('folders')) { $lines.Add(' folders = ' + (& $listLiteral $cfa['folders'])) } if ($cfa.Contains('apps')) { $lines.Add(' apps = ' + (& $listLiteral $cfa['apps'])) } $lines.Add(' }') } if ($PolicyObject.Contains('np')) { $lines.Add(' np = ' + (ConvertTo-AsrPsLiteral $PolicyObject['np'])) } $lines.Add('}') return ($lines -join "`r`n") } function Get-AsrFunctionSource { # Source text of the named top-level functions in this script, plus their Asr* dependencies. param([string[]]$Names) if ($null -eq $AsrRulesBuilderSourceAst) { throw 'Script source is not available.' } $defs = @{} foreach ($f in $AsrRulesBuilderSourceAst.FindAll({ param($a) $a -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $false)) { $defs[$f.Name] = $f } $queue = New-Object 'System.Collections.Generic.Queue[string]' foreach ($n in $Names) { $queue.Enqueue($n) } $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) $order = New-Object 'System.Collections.Generic.List[string]' while ($queue.Count -gt 0) { $n = $queue.Dequeue() if (-not $defs.ContainsKey($n) -or -not $seen.Add($n)) { continue } $order.Add($n) foreach ($cmd in $defs[$n].Body.FindAll({ param($a) $a -is [System.Management.Automation.Language.CommandAst] }, $true)) { $cn = $cmd.GetCommandName() if ($cn -and $defs.ContainsKey($cn)) { $queue.Enqueue($cn) } } } $sorted = @($order) | Sort-Object { $defs[$_].Extent.StartOffset } return ((@($sorted) | ForEach-Object { $defs[$_].Extent.Text }) -join "`r`n`r`n") } function Get-AsrCatalogSource { foreach ($a in $AsrRulesBuilderSourceAst.FindAll({ param($x) $x -is [System.Management.Automation.Language.AssignmentStatementAst] }, $false)) { if ($a.Left.Extent.Text -eq '$AsrRuleCatalog') { return $a.Extent.Text } } throw 'Rule catalog source not found.' } function New-AsrStandaloneScript { # Text of a standalone, offline install script for one policy. It embeds the policy as data # and the same install functions this script uses (copied verbatim from this script). param($PolicyObject, [string]$Encoded, [string]$Generated) $nl = "`r`n" $header = @( '# ASR Rules Builder standalone install script (by MagicSword) - https://asrrules.com/' '#' '# What it does: applies ONE Microsoft Defender Attack Surface Reduction policy to this device' '# with Add-MpPreference / Set-MpPreference, after showing a plan and asking for confirmation.' '# Before changing anything it writes a JSON backup to %ProgramData%\ASR-Rules-Builder\backups.' '# Restore with asr-rules-builder.ps1 -Action Restore. Rules not listed below are left untouched.' '# It works offline: it downloads nothing and runs no dynamic code.' '#' "# Generated: $Generated" "# Encoded policy: $Encoded" '#' '# Usage (elevated PowerShell):' '# powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ [-Force] [-WhatIf]' '# Exit codes: 0 success, 2 environment (or unsafe backup folder), 3 verify mismatch,' '# 4 cancelled (or no console; use -Force), 5 applied with omissions (see the plan).' ) -join $nl $parts = @( $header '[CmdletBinding(SupportsShouldProcess = $true)]' 'param([switch]$Force)' '' 'Set-StrictMode -Version Latest' '$ErrorActionPreference = ''Stop''' '' '# ---- Policy (data) ----' (ConvertTo-AsrPsPolicyLiteral -PolicyObject $PolicyObject) '' '# ---- Rule catalog ----' (Get-AsrCatalogSource) '' '# ---- Install functions (copied from asr-rules-builder.ps1) ----' (Get-AsrFunctionSource -Names @('Invoke-AsrInstall')) '' '$code = Invoke-AsrInstall -PolicyObject $AsrPolicy -Force:$Force -WhatIfMode:([bool]$WhatIfPreference)' 'exit $code' '' ) return ($parts -join $nl) } function Resolve-AsrOutDir { param([string]$OutDir) if ([string]::IsNullOrWhiteSpace($OutDir)) { $root = $env:USERPROFILE if ([string]::IsNullOrEmpty($root)) { $root = $env:HOME } if ([string]::IsNullOrEmpty($root)) { $root = [Environment]::GetFolderPath('UserProfile') } $OutDir = Join-Path $root 'ASR-Rules-Builder' } return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutDir) } function Invoke-AsrSave { param($PolicyObject, [string]$OutDir, [switch]$WhatIfMode) Write-AsrBanner -Subtitle "Save: $($PolicyObject['name'])" $dir = Resolve-AsrOutDir -OutDir $OutDir $slug = Get-AsrPolicySlug -Name $PolicyObject['name'] $encoded = ConvertTo-AsrEncodedPolicy -PolicyObject $PolicyObject $generated = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [System.Globalization.CultureInfo]::InvariantCulture) $doc = [ordered]@{ policy = $PolicyObject; encoded = $encoded; generated = $generated; tool = 'ASR Rules Builder (https://asrrules.com/)' } $jsonPath = Join-Path $dir "$slug.asr-policy.json" $ps1Path = Join-Path $dir "$slug.install.ps1" if ($WhatIfMode) { Write-AsrOk "Policy validated: $(@($PolicyObject['rules'].Keys).Count) rule(s)." Write-AsrInfo "What if: would write the policy JSON to $jsonPath" Write-AsrInfo "What if: would write the offline installer to $ps1Path" Write-AsrInfo 'What if: no files were written.' return 0 } try { [void][System.IO.Directory]::CreateDirectory($dir) [System.IO.File]::WriteAllText($jsonPath, (ConvertTo-AsrJson -Value $doc -Indent 2) + "`n", (New-Object System.Text.UTF8Encoding ($false))) # UTF-8 with BOM so Windows PowerShell 5.1 reads non-ASCII names and paths correctly. [System.IO.File]::WriteAllText($ps1Path, (New-AsrStandaloneScript -PolicyObject $PolicyObject -Encoded $encoded -Generated $generated), (New-Object System.Text.UTF8Encoding ($true))) } catch { Write-AsrFail "Could not write to ${dir}: $($_.Exception.Message)" return 2 } $ruleCount = @($PolicyObject['rules'].Keys).Count Write-AsrOk "Policy validated: $ruleCount rule(s)." Write-AsrOk "Policy JSON: $jsonPath" Write-AsrOk "Offline installer: $ps1Path" Write-Host '' Write-AsrInfo 'Review the installer, then run it from an elevated PowerShell:' Write-Host " powershell.exe -NoProfile -ExecutionPolicy Bypass -File $(ConvertTo-AsrPsLiteral $ps1Path) -WhatIf" -ForegroundColor White return 0 } #endregion #region Status function Invoke-AsrStatus { Write-AsrBanner -Subtitle 'Status' if (-not (Test-AsrDefenderEnvironment -Commands @('Get-MpPreference') -Verb 'Status')) { return 2 } Write-AsrEnvironmentWarnings try { $state = Get-AsrCurrentState } catch { Write-AsrFail "Could not read the Defender configuration: $($_.Exception.Message)"; return 2 } Write-AsrHeader 'ASR rules' if ($state.Rules.Count -eq 0) { Write-AsrInfo 'No ASR rules are configured locally.' } else { Write-Host ((Format-AsrCell 'Rule' 70) + ' ' + (Format-AsrCell 'GUID' 37) + ' Mode') -ForegroundColor DarkGray foreach ($id in $state.Rules.Keys) { $value = $state.Rules[$id] $color = switch ([int]$value) { 1 { 'Green' } 2 { 'Cyan' } 6 { 'Yellow' } default { 'DarkGray' } } Write-Host ((Format-AsrCell (Get-AsrRuleDisplayName -Id $id) 70) + ' ' + (Format-AsrCell $id 37) + ' ' + (Get-AsrRuleModeLabel $value)) -ForegroundColor $color } } $missing = @($AsrRuleCatalog | Where-Object { -not $state.Rules.Contains($_.Id) }) Write-AsrInfo "$($state.Rules.Count) rule(s) configured; $($missing.Count) of $($AsrRuleCatalog.Count) catalog rules not configured." foreach ($m in $missing) { Write-Host " not configured: $($m.ShortName) ($($m.Id))" -ForegroundColor DarkGray } Write-AsrHeader 'ASR-only exclusions' if (-not $state.ExclusionsReadable) { Write-AsrWarn 'Exclusions are hidden from non-administrators. Run elevated to see them.' } if (@($state.AsrOnlyExclusions).Count -eq 0) { Write-AsrInfo 'None.' } foreach ($e in $state.AsrOnlyExclusions) { Write-Host " $e" } if ($state.RuleExclusionsKnown) { Write-AsrHeader 'Per-rule exclusions' if ($state.RuleExclusions.Count -eq 0) { Write-AsrInfo 'None.' } foreach ($id in $state.RuleExclusions.Keys) { foreach ($p in $state.RuleExclusions[$id]) { Write-Host " $(Get-AsrRuleDisplayName -Id $id -Short): $p" } } } Write-AsrHeader 'Controlled folder access' Write-Host " Mode: $(Get-AsrCfaModeLabel $state.CfaMode)" foreach ($f in $state.CfaFolders) { Write-Host " Protected folder: $f" } foreach ($a in $state.CfaApps) { Write-Host " Allowed app: $a" } Write-AsrHeader 'Network protection' Write-Host " Mode: $(Get-AsrNpModeLabel $state.NpMode)" return 0 } #endregion #region Collect $AsrEventLogName = 'Microsoft-Windows-Windows Defender/Operational' $AsrCsvColumns = @('TimeCreated', 'Computer', 'EventId', 'Mode', 'RuleId', 'RuleName', 'Path', 'ProcessName', 'User', 'TargetCommandline', 'ParentCommandline', 'DetectionTime') function Get-AsrXmlText { param($Node) if ($null -eq $Node) { return '' } if ($Node -is [System.Xml.XmlAttribute]) { return [string]$Node.Value } return [string]$Node.InnerText } function ConvertFrom-AsrEventXml { # Pure: one Defender event (XML string from EventLogRecord.ToXml()) -> CSV row object, or $null # when the event is not ASR / CFA / NP related. param([Parameter(Mandatory = $true)][string]$Xml) $doc = New-Object System.Xml.XmlDocument $doc.XmlResolver = $null $doc.LoadXml($Xml) $sys = "/*[local-name()='Event']/*[local-name()='System']" $eventId = [int](Get-AsrXmlText $doc.SelectSingleNode("$sys/*[local-name()='EventID']")) $timeNode = $doc.SelectSingleNode("$sys/*[local-name()='TimeCreated']/@SystemTime") $computer = Get-AsrXmlText $doc.SelectSingleNode("$sys/*[local-name()='Computer']") $sid = Get-AsrXmlText $doc.SelectSingleNode("$sys/*[local-name()='Security']/@UserID") $data = @{} foreach ($d in $doc.SelectNodes("/*[local-name()='Event']/*[local-name()='EventData']/*[local-name()='Data']")) { $nameAttr = $d.Attributes.GetNamedItem('Name') if ($null -eq $nameAttr) { continue } $key = ($nameAttr.Value -replace '\s', '').ToLowerInvariant() if (-not $data.ContainsKey($key)) { $data[$key] = [string]$d.InnerText } } $get = { param([string[]]$keys) foreach ($k in $keys) { if ($data.ContainsKey($k) -and $data[$k]) { return $data[$k] } }; return '' } $time = '' if ($timeNode) { $parsed = [DateTime]::Parse($timeNode.Value, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]'AdjustToUniversal, AssumeUniversal') $time = $parsed.ToString('yyyy-MM-ddTHH:mm:ss.fffZ', [System.Globalization.CultureInfo]::InvariantCulture) } $mode = ''; $ruleId = ''; $ruleName = '' $path = & $get @('path'); $process = & $get @('processname') $target = & $get @('targetcommandline'); $parent = & $get @('parentcommandline') switch ($eventId) { 1121 { $mode = 'Block' } 1122 { $mode = 'Audit' } 1129 { $mode = 'UserOverride' } 1123 { $mode = 'Block'; $ruleId = 'cfa'; $ruleName = 'Controlled folder access' } 1124 { $mode = 'Audit'; $ruleId = 'cfa'; $ruleName = 'Controlled folder access' } 1125 { $mode = 'Audit'; $ruleId = 'network-protection'; $ruleName = 'Network protection' } 1126 { $mode = 'Block'; $ruleId = 'network-protection'; $ruleName = 'Network protection' } 5007 { $mode = 'ConfigChange' } default { return $null } } if ($eventId -in 1121, 1122, 1129) { $ruleId = (& $get @('id')).Trim().Trim('{', '}').ToLowerInvariant() $ruleName = Get-AsrRuleDisplayName -Id $ruleId } if ($eventId -eq 1125 -or $eventId -eq 1126) { if (-not $path) { $path = & $get @('domain', 'url', 'destination') } } if ($eventId -eq 5007) { $old = & $get @('oldvalue'); $new = & $get @('newvalue') $both = "$old $new" if ($both -notmatch '(?i)Windows Defender Exploit Guard|ASRRules|ASROnly|AttackSurfaceReduction|ControlledFolderAccess|NetworkProtection') { return $null } $guid = [regex]::Match($both, '(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') if ($guid.Success -and $null -ne (Get-AsrRule -Id $guid.Value)) { $ruleId = $guid.Value.ToLowerInvariant(); $ruleName = Get-AsrRuleDisplayName -Id $ruleId } elseif ($both -match '(?i)Controlled Folder Access|ControlledFolderAccess') { $ruleId = 'cfa'; $ruleName = 'Controlled folder access' } elseif ($both -match '(?i)Network Protection|NetworkProtection') { $ruleId = 'network-protection'; $ruleName = 'Network protection' } else { $ruleName = 'ASR configuration' } # Path carries the changed setting: the new value, or the old one when it was removed. $path = if ($new) { $new } else { $old } $process = ''; $target = ''; $parent = '' } $user = & $get @('user') if (-not $user) { $user = $sid } return [pscustomobject][ordered]@{ TimeCreated = $time Computer = $computer EventId = $eventId Mode = $mode RuleId = $ruleId RuleName = $ruleName Path = $path ProcessName = $process User = $user TargetCommandline = $target ParentCommandline = $parent DetectionTime = (& $get @('detectiontime')) } } function ConvertTo-AsrCsvField { param([AllowNull()][object]$Value) $text = if ($null -eq $Value) { '' } else { [string]$Value } # Spreadsheet formula injection guard: event fields are attacker-influenced. Excel and others # also treat a leading TAB or CR as the start of a formula. if ($text.Length -gt 0 -and ('=+-@'.IndexOf($text[0]) -ge 0 -or $text[0] -eq [char]0x09 -or $text[0] -eq [char]0x0D)) { $text = "'" + $text } return '"' + $text.Replace('"', '""') + '"' } function ConvertTo-AsrCsvText { # Pure: rows -> CSV text with the contract column order (header always present). param([object[]]$Rows) $lines = New-Object 'System.Collections.Generic.List[string]' $lines.Add((($AsrCsvColumns | ForEach-Object { '"' + $_ + '"' }) -join ',')) foreach ($row in @($Rows)) { if ($null -eq $row) { continue } $lines.Add((($AsrCsvColumns | ForEach-Object { ConvertTo-AsrCsvField $row.$_ }) -join ',')) } return (($lines -join "`r`n") + "`r`n") } function Get-AsrTopCounts { param([object[]]$Rows, [string]$Property, [int]$Top = 10) $groups = @($Rows | Where-Object { $_.$Property } | Group-Object -Property $Property) $sorted = @($groups | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false }) return @($sorted | Select-Object -First $Top | ForEach-Object { [pscustomobject]@{ Name = $_.Name; Count = $_.Count } }) } function Get-AsrEventAnalysis { # Pure: summary of event rows. AuditRuleIds = rules configured in audit mode (for "zero hits"). param([object[]]$Events, [string[]]$AuditRuleIds = @(), [int]$Top = 10) $all = @(@($Events) | Where-Object { $null -ne $_ }) $detections = @($all | Where-Object { $_.Mode -ne 'ConfigChange' }) $byMode = [ordered]@{ Block = 0; Audit = 0; UserOverride = 0; ConfigChange = 0 } foreach ($e in $all) { if ($byMode.Contains($e.Mode)) { $byMode[$e.Mode]++ } } $rules = @() foreach ($g in @($detections | Where-Object { $_.RuleId } | Group-Object -Property RuleId)) { $items = @($g.Group) $rules += [pscustomobject]@{ RuleId = $g.Name RuleName = $items[0].RuleName Total = $items.Count Block = @($items | Where-Object { $_.Mode -eq 'Block' }).Count Audit = @($items | Where-Object { $_.Mode -eq 'Audit' }).Count UserOverride = @($items | Where-Object { $_.Mode -eq 'UserOverride' }).Count } } $rules = @($rules | Sort-Object -Property @{ Expression = 'Total'; Descending = $true }, @{ Expression = 'RuleName'; Descending = $false }) $perDay = @(@($all | Where-Object { $_.TimeCreated -and $_.TimeCreated.Length -ge 10 } | Group-Object -Property { $_.TimeCreated.Substring(0, 10) }) | Sort-Object -Property Name | ForEach-Object { [pscustomobject]@{ Day = $_.Name; Count = $_.Count } }) $zero = @() foreach ($id in @($AuditRuleIds)) { if (-not $id) { continue } $key = $id.ToLowerInvariant() if (@($detections | Where-Object { $_.RuleId -eq $key }).Count -eq 0) { $zero += [pscustomobject]@{ RuleId = $key; RuleName = (Get-AsrRuleDisplayName -Id $key) } } } return [pscustomobject]@{ Total = $all.Count Detections = $detections.Count ByMode = $byMode Rules = $rules TopProcesses = @(Get-AsrTopCounts -Rows $detections -Property 'ProcessName' -Top $Top) TopPaths = @(Get-AsrTopCounts -Rows $detections -Property 'Path' -Top $Top) TopUsers = @(Get-AsrTopCounts -Rows $detections -Property 'User' -Top $Top) PerDay = $perDay ZeroHitAuditRules = $zero } } function Write-AsrAnalysis { param($Analysis, [int]$Days) Write-AsrHeader "Analysis (last $Days day(s))" if ($Analysis.Total -eq 0) { Write-AsrInfo "No ASR, Controlled folder access or Network protection events in the last $Days day(s)." } else { $parts = @(); foreach ($k in $Analysis.ByMode.Keys) { $parts += "$k $($Analysis.ByMode[$k])" } Write-Host " $($Analysis.Total) event(s): $($parts -join ', ')" } if (@($Analysis.Rules).Count -gt 0) { Write-AsrHeader 'Noisiest rules' Write-Host ((Format-AsrCell 'Rule' 56) + ' Total Block Audit Override') -ForegroundColor DarkGray foreach ($r in @($Analysis.Rules | Select-Object -First 10)) { $label = $r.RuleName; $known = Get-AsrRule -Id $r.RuleId; if ($null -ne $known) { $label = $known.ShortName } Write-Host ((Format-AsrCell $label 56) + ' ' + ([string]$r.Total).PadLeft(5) + ' ' + ([string]$r.Block).PadLeft(5) + ' ' + ([string]$r.Audit).PadLeft(5) + ' ' + ([string]$r.UserOverride).PadLeft(8)) } } foreach ($section in @(@('Top processes', 'TopProcesses'), @('Top target paths', 'TopPaths'), @('Top users', 'TopUsers'))) { $items = @($Analysis.($section[1])) if ($items.Count -eq 0) { continue } Write-AsrHeader $section[0] foreach ($i in $items) { Write-Host (' ' + ([string]$i.Count).PadLeft(6) + ' ' + $i.Name) } } if (@($Analysis.PerDay).Count -gt 0) { Write-AsrHeader 'Events per day' $max = (@($Analysis.PerDay) | Measure-Object -Property Count -Maximum).Maximum foreach ($d in $Analysis.PerDay) { $bar = '#' * [Math]::Max(1, [int][Math]::Round(40 * $d.Count / [Math]::Max(1, $max))) Write-Host (' ' + $d.Day + ' ' + ([string]$d.Count).PadLeft(6) + ' ') -NoNewline Write-Host $bar -ForegroundColor DarkCyan } } Write-AsrHeader 'Audit rules with zero hits (candidates for block)' if (@($Analysis.ZeroHitAuditRules).Count -eq 0) { Write-AsrInfo 'None (or no audit-mode rules known).' } foreach ($z in $Analysis.ZeroHitAuditRules) { Write-Host " $($z.RuleName) ($($z.RuleId))" -ForegroundColor Green } } function Get-AsrAuditRuleIds { param($PolicyObject) if ($null -ne $PolicyObject) { return @($PolicyObject['rules'].Keys | Where-Object { $PolicyObject['rules'][$_] -ceq 'audit' }) } try { if (Get-Command -Name Get-MpPreference -ErrorAction SilentlyContinue) { $state = Get-AsrCurrentState return @($state.Rules.Keys | Where-Object { [int]$state.Rules[$_] -eq 2 }) } } catch { $null = $_ } return @() } function Invoke-AsrCollect { param([string]$OutDir, [int]$Days = 30, $PolicyObject, [switch]$WhatIfMode) Write-AsrBanner -Subtitle "Collect: last $Days day(s)" if (-not (Get-Command -Name Get-WinEvent -ErrorAction SilentlyContinue)) { Write-AsrFail 'Collect requires Windows (Get-WinEvent is not available).' return 2 } $filter = @{ LogName = $AsrEventLogName; Id = @(1121, 1122, 1123, 1124, 1125, 1126, 1129, 5007); StartTime = (Get-Date).AddDays(-$Days) } $raw = @() try { $raw = @(Get-WinEvent -FilterHashtable $filter -ErrorAction Stop) } catch { $id = [string]$_.FullyQualifiedErrorId $msg = [string]$_.Exception.Message if ($id -like 'NoMatchingEventsFound*' -or $msg -match 'No events were found') { $raw = @() } elseif ($_.Exception -is [System.UnauthorizedAccessException] -or $id -match 'UnauthorizedAccess' -or $msg -match '(?i)unauthorized|access is denied') { Write-AsrWarn "Access denied reading '$AsrEventLogName'. Run elevated or add the account to the Event Log Readers group." return 2 } else { Write-AsrFail "Could not read '$AsrEventLogName': $msg" return 2 } } $rows = New-Object 'System.Collections.Generic.List[object]' foreach ($e in $raw) { try { $row = ConvertFrom-AsrEventXml -Xml ($e.ToXml()) if ($null -ne $row) { $rows.Add($row) } } catch { Write-AsrWarn "Skipped an unreadable event: $($_.Exception.Message)" } } $sorted = @($rows | Sort-Object -Property TimeCreated) $dir = Resolve-AsrOutDir -OutDir $OutDir $computer = $env:COMPUTERNAME if ([string]::IsNullOrEmpty($computer)) { $computer = [Environment]::MachineName } $computer = [regex]::Replace($computer, '[^A-Za-z0-9._-]', '_') $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss', [System.Globalization.CultureInfo]::InvariantCulture) $csvPath = Join-Path $dir "asr-events-$computer-$stamp.csv" if ($WhatIfMode) { Write-AsrInfo "What if: would write $($sorted.Count) event(s) to $csvPath (no file was written)." $analysis = Get-AsrEventAnalysis -Events $sorted -AuditRuleIds @(Get-AsrAuditRuleIds -PolicyObject $PolicyObject) Write-AsrAnalysis -Analysis $analysis -Days $Days return 0 } try { [void][System.IO.Directory]::CreateDirectory($dir) # UTF-8 with BOM so Excel opens non-ASCII paths correctly. [System.IO.File]::WriteAllText($csvPath, (ConvertTo-AsrCsvText -Rows $sorted), (New-Object System.Text.UTF8Encoding ($true))) } catch { Write-AsrFail "Could not write ${csvPath}: $($_.Exception.Message)" return 2 } Write-AsrOk "$($sorted.Count) event(s) written to $csvPath" $analysis = Get-AsrEventAnalysis -Events $sorted -AuditRuleIds @(Get-AsrAuditRuleIds -PolicyObject $PolicyObject) Write-AsrAnalysis -Analysis $analysis -Days $Days Write-Host '' Write-AsrInfo 'Upload the CSV on the ASR Rules Builder "Event analysis" page for charts (it stays in your browser).' return 0 } #endregion #region Restore function ConvertFrom-AsrBackupText { # Validates a backup JSON document and returns a state object (same shape as Get-AsrCurrentState). param([string]$Text) try { $tree = ConvertFrom-AsrJsonText -Text $Text } catch { throw "The backup is not valid JSON ($($_.Exception.Message))." } if (-not (Test-AsrIsJsonObject $tree) -or -not $tree.Contains('tool') -or $tree['tool'] -cne 'ASR Rules Builder') { throw 'This file is not an ASR Rules Builder backup.' } $rules = [ordered]@{} if (-not ($tree.Contains('rules') -and (Test-AsrIsJsonArray $tree['rules']))) { throw 'The backup has no rules list.' } foreach ($r in $tree['rules']) { if (-not (Test-AsrIsJsonObject $r) -or -not $r.Contains('id') -or -not $r.Contains('action')) { throw 'The backup has an invalid rule entry.' } $id = $r['id']; $act = $r['action'] if ($id -isnot [string] -or $id -cnotmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { throw "The backup has an invalid rule id '$id'." } if ($act -isnot [double] -or @(0, 1, 2, 5, 6) -notcontains [int]$act -or [int]$act -ne $act) { throw "The backup has an invalid action for rule $id." } $rules[$id] = [int]$act } $readList = { param($key, $where) if (-not $tree.Contains($key) -or $null -eq $tree[$key]) { return , @() } return , (ConvertTo-AsrEntryList -Value $tree[$key] -Where $where) } $excl = & $readList 'asrOnlyExclusions' 'Backup exclusion' $cfaMode = $null; $folders = @(); $apps = @() if ($tree.Contains('cfa') -and $null -ne $tree['cfa']) { $c = $tree['cfa'] if (-not (Test-AsrIsJsonObject $c) -or -not $c.Contains('mode') -or $c['mode'] -isnot [double] -or @(0, 1, 2, 3, 4) -notcontains [int]$c['mode']) { throw 'The backup has an invalid Controlled folder access entry.' } $cfaMode = [int]$c['mode'] if ($c.Contains('folders')) { $folders = ConvertTo-AsrEntryList -Value $c['folders'] -Where 'Backup protected folder' } if ($c.Contains('apps')) { $apps = ConvertTo-AsrEntryList -Value $c['apps'] -Where 'Backup allowed app' } } $npMode = $null if ($tree.Contains('np') -and $null -ne $tree['np']) { if ($tree['np'] -isnot [double] -or @(0, 1, 2) -notcontains [int]$tree['np']) { throw 'The backup has an invalid Network protection entry.' } $npMode = [int]$tree['np'] } # Per-rule exclusions: only in backups written by versions that read them. Absent = unknown, # so Restore leaves the device's per-rule exclusions alone. $ruleExcl = [ordered]@{} $ruleExclKnown = $false if ($tree.Contains('ruleExclusions') -and $null -ne $tree['ruleExclusions']) { $re = $tree['ruleExclusions'] if (-not (Test-AsrIsJsonObject $re)) { throw 'The backup has an invalid per-rule exclusions entry.' } foreach ($id in $re.Keys) { if ($id -cnotmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { throw "The backup has an invalid per-rule exclusion rule id '$id'." } $list = ConvertTo-AsrEntryList -Value $re[$id] -Where "Backup per-rule exclusion for $id" if ($list.Count -gt 0) { $ruleExcl[$id] = [string[]]$list } } $ruleExclKnown = $true } $readable = $true if ($tree.Contains('exclusionsReadable') -and $tree['exclusionsReadable'] -is [bool]) { $readable = $tree['exclusionsReadable'] } return [pscustomobject]@{ Rules = $rules AsrOnlyExclusions = [string[]]@($excl) RuleExclusions = $ruleExcl RuleExclusionsKnown = $ruleExclKnown CfaMode = $cfaMode CfaFolders = [string[]]@($folders) CfaApps = [string[]]@($apps) NpMode = $npMode ExclusionsReadable = $readable Created = $(if ($tree.Contains('created')) { [string]$tree['created'] } else { '' }) Computer = $(if ($tree.Contains('computer')) { [string]$tree['computer'] } else { '' }) } } function New-AsrRestorePlan { # Pure: what Restore will change to bring $Current back to $Backup. param($Backup, $Current) $rows = New-Object 'System.Collections.Generic.List[object]' foreach ($id in $Backup.Rules.Keys) { $cur = if ($Current.Rules.Contains($id)) { $Current.Rules[$id] } else { $null } $rows.Add([pscustomobject]@{ Kind = 'Rule'; Key = $id; Label = (Get-AsrRuleDisplayName -Id $id -Short); Current = (Get-AsrRuleModeLabel $cur); New = (Get-AsrRuleModeLabel $Backup.Rules[$id]); Change = ($null -eq $cur -or [int]$cur -ne [int]$Backup.Rules[$id]); Note = '' }) } foreach ($id in $Current.Rules.Keys) { if (-not $Backup.Rules.Contains($id)) { $rows.Add([pscustomobject]@{ Kind = 'RemoveRule'; Key = $id; Label = (Get-AsrRuleDisplayName -Id $id -Short); Current = (Get-AsrRuleModeLabel $Current.Rules[$id]); New = 'Not configured'; Change = $true; Note = '' }) } } $canDiffLists = ($Backup.ExclusionsReadable -and $Current.ExclusionsReadable) foreach ($spec in @(@('Exclusion', 'ASR exclusion', 'AsrOnlyExclusions'), @('CfaFolder', 'Protected folder', 'CfaFolders'), @('CfaApp', 'Allowed app', 'CfaApps'))) { foreach ($p in $Backup.($spec[2])) { if (-not (Test-AsrListContains $Current.($spec[2]) $p)) { $rows.Add([pscustomobject]@{ Kind = $spec[0]; Key = $p; Label = "$($spec[1]): $p"; Path = $p; Current = 'Absent'; New = 'Present'; Change = $true; Note = '' }) } } if ($canDiffLists) { foreach ($p in $Current.($spec[2])) { if (-not (Test-AsrListContains $Backup.($spec[2]) $p)) { $rows.Add([pscustomobject]@{ Kind = 'Remove' + $spec[0]; Key = $p; Label = "$($spec[1]): $p"; Path = $p; Current = 'Present'; New = 'Absent'; Change = $true; Note = '' }) } } } } $reKnown = ($Backup.PSObject.Properties['RuleExclusionsKnown'] -and $Backup.RuleExclusionsKnown -and $Current.PSObject.Properties['RuleExclusionsKnown'] -and $Current.RuleExclusionsKnown) if ($reKnown) { foreach ($id in $Backup.RuleExclusions.Keys) { foreach ($p in $Backup.RuleExclusions[$id]) { if (-not (Test-AsrRuleExclusionPresent -State $Current -Id $id -Path $p)) { $rows.Add([pscustomobject]@{ Kind = 'RuleExclusion'; Key = "$id|$p"; Label = ((Get-AsrRuleDisplayName -Id $id -Short) + " exclusion: $p"); Path = $p; Current = 'Absent'; New = 'Present'; Change = $true; Note = '' }) } } } if ($canDiffLists) { foreach ($id in $Current.RuleExclusions.Keys) { foreach ($p in $Current.RuleExclusions[$id]) { if (-not (Test-AsrRuleExclusionPresent -State $Backup -Id $id -Path $p)) { $rows.Add([pscustomobject]@{ Kind = 'RemoveRuleExclusion'; Key = "$id|$p"; Label = ((Get-AsrRuleDisplayName -Id $id -Short) + " exclusion: $p"); Path = $p; Current = 'Present'; New = 'Absent'; Change = $true; Note = '' }) } } } } } if ($null -ne $Backup.CfaMode) { $rows.Add([pscustomobject]@{ Kind = 'CfaMode'; Key = 'cfa'; Label = 'Controlled folder access'; Current = (Get-AsrCfaModeLabel $Current.CfaMode); New = (Get-AsrCfaModeLabel $Backup.CfaMode); Change = ($Current.CfaMode -ne $Backup.CfaMode); Note = '' }) } if ($null -ne $Backup.NpMode) { $rows.Add([pscustomobject]@{ Kind = 'NetworkProtection'; Key = 'np'; Label = 'Network protection'; Current = (Get-AsrNpModeLabel $Current.NpMode); New = (Get-AsrNpModeLabel $Backup.NpMode); Change = ($Current.NpMode -ne $Backup.NpMode); Note = '' }) } return $rows.ToArray() } function Invoke-AsrApplyRestore { param($Backup, [object[]]$Plan) $errors = New-Object 'System.Collections.Generic.List[string]' $step = { param([string]$what, [scriptblock]$do) try { & $do } catch { $errors.Add("${what}: $($_.Exception.Message)") } } $ids = @($Backup.Rules.Keys) if ($ids.Count -gt 0) { $actions = @($ids | ForEach-Object { Get-AsrRuleActionName ([int]$Backup.Rules[$_]) }) & $step 'ASR rules' { Add-MpPreference -AttackSurfaceReductionRules_Ids $ids -AttackSurfaceReductionRules_Actions $actions -ErrorAction Stop } } $remove = @($Plan | Where-Object { $_.Kind -eq 'RemoveRule' } | ForEach-Object { $_.Key }) if ($remove.Count -gt 0) { & $step 'Remove ASR rules' { Remove-MpPreference -AttackSurfaceReductionRules_Ids $remove -ErrorAction Stop } } $map = @{ Exclusion = 'AttackSurfaceReductionOnlyExclusions' CfaFolder = 'ControlledFolderAccessProtectedFolders' CfaApp = 'ControlledFolderAccessAllowedApplications' } foreach ($kind in @('Exclusion', 'CfaFolder', 'CfaApp')) { $add = [string[]]@($Plan | Where-Object { $_.Kind -eq $kind } | ForEach-Object { $_.Key }) $del = [string[]]@($Plan | Where-Object { $_.Kind -eq "Remove$kind" } | ForEach-Object { $_.Key }) if ($add.Count -gt 0) { $splat = @{ $map[$kind] = $add; ErrorAction = 'Stop' }; & $step "Add $kind" { Add-MpPreference @splat } } if ($del.Count -gt 0) { $splatDel = @{ $map[$kind] = $del; ErrorAction = 'Stop' }; & $step "Remove $kind" { Remove-MpPreference @splatDel } } } # Per-rule exclusions. Keys are "|" ('|' cannot occur in a Windows path). # Add-MpPreference takes parallel arrays; Remove-MpPreference takes one id and one path per call # and matches the path case-sensitively, so removal uses the path exactly as Get-MpPreference returned it. $reAdd = @($Plan | Where-Object { $_.Kind -eq 'RuleExclusion' }) if ($reAdd.Count -gt 0) { $splatRe = @{ AttackSurfaceReductionRules_RuleSpecificExclusions_Id = [string[]]@($reAdd | ForEach-Object { $_.Key.Substring(0, $_.Key.IndexOf('|')) }) AttackSurfaceReductionRules_RuleSpecificExclusions = [string[]]@($reAdd | ForEach-Object { $_.Key.Substring($_.Key.IndexOf('|') + 1) }) ErrorAction = 'Stop' } & $step 'Add per-rule exclusions' { Add-MpPreference @splatRe } } foreach ($row in @($Plan | Where-Object { $_.Kind -eq 'RemoveRuleExclusion' })) { $splatReDel = @{ AttackSurfaceReductionRules_RuleSpecificExclusions_Id = $row.Key.Substring(0, $row.Key.IndexOf('|')) AttackSurfaceReductionRules_RuleSpecificExclusions = $row.Key.Substring($row.Key.IndexOf('|') + 1) ErrorAction = 'Stop' } & $step "Remove per-rule exclusion $($row.Label)" { Remove-MpPreference @splatReDel } } if ($null -ne $Backup.CfaMode) { & $step 'Controlled folder access' { Set-MpPreference -EnableControlledFolderAccess (Get-AsrCfaActionName $Backup.CfaMode) -ErrorAction Stop } } if ($null -ne $Backup.NpMode) { & $step 'Network protection' { Set-MpPreference -EnableNetworkProtection (Get-AsrNpActionName $Backup.NpMode) -ErrorAction Stop } } return $errors.ToArray() } function Invoke-AsrRestore { param([string]$BackupPath, [switch]$Force, [switch]$WhatIfMode) Write-AsrBanner -Subtitle 'Restore' if (-not (Test-AsrDefenderEnvironment -RequireElevation -Commands @('Get-MpPreference', 'Add-MpPreference', 'Set-MpPreference', 'Remove-MpPreference') -Verb 'Restore')) { return 2 } if ([string]::IsNullOrWhiteSpace($BackupPath)) { # The backup folder decides what gets applied: refuse it when it is a link or not owned by # administrators, and lock down a loose access list (only reported under -WhatIf). try { $dir = Initialize-AsrBackupDirectory -ReadOnly:$WhatIfMode } catch { Write-AsrFail $_.Exception.Message; return 2 } # Newest by write time: by name alone 'asr-backup-.json' sorts after its same-second sibling '-1.json'. # Write times can be set by whoever owns a file, so files that are not trusted are skipped first. $all = @(Get-ChildItem -LiteralPath $dir -Filter 'asr-backup-*.json' -File -Force -ErrorAction SilentlyContinue) $trusted = @() foreach ($f in $all) { $problem = Get-AsrBackupTrustProblem -Path $f.FullName if ($problem) { Write-AsrWarn "Ignoring untrusted backup $($f.FullName): $problem." } else { $trusted += $f } } $newest = @($trusted | Sort-Object -Property @{ Expression = 'LastWriteTimeUtc'; Descending = $true }, @{ Expression = { $_.Name.Length }; Descending = $true }, @{ Expression = 'Name'; Descending = $true } | Select-Object -First 1) if ($newest.Count -eq 0) { if ($all.Count -gt 0) { Write-AsrFail "No trusted backups found in $dir ($($all.Count) untrusted file(s) ignored)." } else { Write-AsrFail "No backups found in $dir." } return 1 } $BackupPath = $newest[0].FullName } $BackupPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($BackupPath) if (-not (Test-Path -LiteralPath $BackupPath -PathType Leaf)) { Write-AsrFail "Backup not found: $BackupPath"; return 1 } try { $backup = ConvertFrom-AsrBackupText -Text (Read-AsrTrustedBackupText -Path $BackupPath) } catch { Write-AsrFail "Backup rejected: $($_.Exception.Message)"; return 1 } Write-AsrInfo "Backup: $BackupPath" Write-AsrInfo "Created $($backup.Created) on $($backup.Computer); $($backup.Rules.Count) rule(s), $(@($backup.AsrOnlyExclusions).Count) ASR exclusion(s)." Write-AsrEnvironmentWarnings try { $current = Get-AsrCurrentState } catch { Write-AsrFail "Could not read the current Defender configuration: $($_.Exception.Message)"; return 2 } $plan = @(New-AsrRestorePlan -Backup $backup -Current $current) Write-AsrPlan -Plan $plan -Title 'Restore plan' -Footer 'Rules that are not in the backup are removed (Not configured).' if (-not $backup.RuleExclusionsKnown -and $current.RuleExclusionsKnown -and $current.RuleExclusions.Count -gt 0) { Write-AsrWarn 'This backup has no per-rule exclusion data (older ASR Rules Builder version); per-rule exclusions on this device are left as they are.' } if ($WhatIfMode) { Write-AsrInfo 'What if: no changes were made.'; return 0 } if (-not $Force) { if (-not (Read-AsrConfirmation 'Are you sure you want to restore this ASR backup? [y/N]')) { Write-AsrWarn 'Cancelled. Nothing was changed.' return 4 } } $errors = @(Invoke-AsrApplyRestore -Backup $backup -Plan $plan) foreach ($e in $errors) { Write-AsrFail $e } try { $after = Get-AsrCurrentState } catch { Write-AsrFail "Could not re-read the Defender configuration: $($_.Exception.Message)"; return 3 } $verify = @(New-AsrRestorePlan -Backup $backup -Current $after | Where-Object { $_.Change }) if ($errors.Count -gt 0 -or $verify.Count -gt 0) { foreach ($v in $verify) { Write-AsrFail "$($v.Label): expected $($v.New), found $($v.Current)" } Write-AsrFail 'Restore finished with differences.' return 3 } Write-AsrOk 'Backup restored and verified.' return 0 } #endregion #region Entry point function Invoke-AsrRulesBuilder { # Runs one action and returns the contract exit code. param( [string]$Action = 'Save', [string]$Policy, [string]$OutDir, [int]$Days = 30, [switch]$Force, [string]$BackupPath, [switch]$WhatIfMode ) try { $policyObject = $null if ($Action -in @('Save', 'Install') -and [string]::IsNullOrWhiteSpace($Policy)) { Write-AsrFail "-Policy is required for -Action $Action. Copy the command from the ASR Rules Builder policy builder." return 1 } if (-not [string]::IsNullOrWhiteSpace($Policy)) { try { $policyObject = ConvertFrom-AsrEncodedPolicy -Encoded $Policy.Trim() } catch { Write-AsrFail "Policy rejected: $($_.Exception.Message)" return 1 } } switch ($Action) { 'Save' { return (Invoke-AsrSave -PolicyObject $policyObject -OutDir $OutDir -WhatIfMode:$WhatIfMode) } 'Install' { return (Invoke-AsrInstall -PolicyObject $policyObject -Force:$Force -WhatIfMode:$WhatIfMode) } 'Status' { return (Invoke-AsrStatus) } 'Collect' { return (Invoke-AsrCollect -OutDir $OutDir -Days $Days -PolicyObject $policyObject -WhatIfMode:$WhatIfMode) } 'Restore' { return (Invoke-AsrRestore -BackupPath $BackupPath -Force:$Force -WhatIfMode:$WhatIfMode) } } Write-AsrFail "Unknown action '$Action'." return 1 } catch { Write-AsrFail "Unexpected error: $($_.Exception.Message)" return 2 } } # Test hook (internal): scripts/Test-AsrRulesBuilder.ps1 sets ASR_RULES_BUILDER_LOAD_ONLY=1 and dot-sources this # file to load the functions without running an action. Set anywhere else (for example left over # in a machine environment), it must not turn a real run into a silent success. $asrLoadOnly = ($env:ASR_RULES_BUILDER_LOAD_ONLY -eq '1') if ($asrLoadOnly -and $MyInvocation.InvocationName -eq '.') { return } if ($asrLoadOnly) { [Console]::Error.WriteLine('ASR Rules Builder: WARNING: the ASR_RULES_BUILDER_LOAD_ONLY environment variable is set to 1. It is an internal test hook, so NOTHING was done. Remove it (Remove-Item Env:ASR_RULES_BUILDER_LOAD_ONLY) and run the command again.') $asrExitCode = 2 } else { $asrExitCode = @(Invoke-AsrRulesBuilder -Action $Action -Policy $Policy -OutDir $OutDir -Days $Days -Force:$Force -BackupPath $BackupPath -WhatIfMode:([bool]$WhatIfPreference))[-1] } if ($MyInvocation.MyCommand.CommandType -eq 'ExternalScript') { exit $asrExitCode } # Run through [scriptblock]::Create((irm ...)): do not close the user's window. $global:LASTEXITCODE = $asrExitCode if ($asrExitCode -ne 0) { Write-Host "ASR Rules Builder finished with exit code $asrExitCode (see `$LASTEXITCODE)." -ForegroundColor DarkGray } #endregion