# -- Providence Shield - CURE for Windows: check a PC for known malware and hijacked settings --------------------- # irm https://api.providenceai.pro/shield/cure.ps1 | iex # (or double-click cure.cmd from https://providenceai.pro/cure) # Undo: & ([scriptblock]::Create((irm https://api.providenceai.pro/shield/cure.ps1))) -Restore # Deep scan: & ([scriptblock]::Create((irm https://api.providenceai.pro/shield/cure.ps1))) -Full # # Free. Runs on YOUR PC. Our script uploads nothing; Microsoft Defender's own cloud sample submission follows this # PC's settings. # # What it does, exactly: # 1. Your own account (before asking for administrator rights): proxy settings, start-up entries, Startup folder. # 2. As administrator: hosts file and system proxy, antivirus state and Defender exclusions, computer-wide # start-up entries; a report-only list of recent scheduled tasks, services and WMI subscriptions. # 3. A Microsoft scanner: Microsoft Defender (update + scan). If Defender is not the active antivirus it offers # to download Microsoft Safety Scanner instead (checked to be signed by Microsoft right before it runs). # 4. Optional: Microsoft Defender Offline (restarts the PC). # # Rules this script keeps: # - It never says a PC is clean. It says which scanner ran, what it found, and what did not run. # - A pattern match of ours is "looks suspicious - review", never "virus". Nothing of ours changes without a # question about that one item (default answer: No). # - Every change WE make is recorded so -Restore can put it back: your account's changes in # %USERPROFILE%\.providence-shield, computer-wide ones in %ProgramData%\ProvidenceShield (administrators only). # - What -Restore cannot undo: anything Microsoft Defender or Safety Scanner removed (see Windows Security > # Protection history), and a restart into Defender Offline. # # Unattended use (tests): SHIELD_ANSWER=y|n answers every question; the proxy questions additionally need # SHIELD_ANSWER_PROXY=y. Nothing is switched off unattended without those. # # Everything lives in one script block, so no function or variable is left behind in your PowerShell session. & { param([switch]$Restore, [switch]$Full, [switch]$NoOffline, [switch]$MachineOnly, [string]$UserDir = "", [string]$Stamp = "") if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { Write-Host "This PC runs PowerShell in a restricted mode ($($ExecutionContext.SessionState.LanguageMode)), usually set by an employer or school." -ForegroundColor Yellow Write-Host "Providence Shield cannot run here and nothing was checked. Ask your IT department, or use Windows Security > Virus & threat protection > Quick scan." return } $ErrorActionPreference = "Continue" $ProgressPreference = "SilentlyContinue" # local to this script block: your session's setting is untouched $SELF = "https://api.providenceai.pro/shield/cure.ps1" $PSEXE = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe" try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 } catch {} # TLS 1.2 on old Windows $Restore = [bool]$Restore; $Full = [bool]$Full; $NoOffline = [bool]$NoOffline; $MachineOnly = [bool]$MachineOnly if ($env:SHIELD_ANSWER) { if ($env:SHIELD_RESTORE) { $Restore = $true }; $NoOffline = $true } $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if ($MachineOnly -and -not $isAdmin) { Write-Host "The computer-wide part needs administrator rights. Nothing was checked." -ForegroundColor Red; return } if (-not $UserDir) { $UserDir = $env:USERPROFILE } if ($Stamp -notmatch '^\d{4}-\d\d-\d\d_\d{6}$') { $Stamp = Get-Date -Format "yyyy-MM-dd_HHmmss" } $USH = Join-Path $UserDir ".providence-shield" $UQ = Join-Path $USH "quarantine\$Stamp" $AdminRoot = Join-Path $env:ProgramData "ProvidenceShield" $MQ = Join-Path $AdminRoot "quarantine\$Stamp" $S = @{ found = 0; removed = 0; susp = 0; fixed = 0; review = 0; okby = @(); notrun = @(); report = $null; lastOk = $false; mtrust = $false; cnt = 0; defenderOk = $false uman = (Join-Path $UQ "manifest.json"); mman = (Join-Path $MQ "manifest.json") uchanges = (New-Object System.Collections.ArrayList); mchanges = (New-Object System.Collections.ArrayList) } function Say($t, $c = "Gray") { Write-Host $t -ForegroundColor $c if ($S.report) { try { Add-Content -LiteralPath $S.report -Value $t -Encoding UTF8 -ErrorAction Stop } catch {} } } function Hdr($t) { Say ""; Say "== $t" "Yellow" } # SHIELD_ANSWER answers every question in unattended runs; $needVar names an extra variable a sensitive question needs. function Ask($q, $needVar) { if ($env:SHIELD_ANSWER) { $ans = $env:SHIELD_ANSWER if ($needVar) { $ans = [Environment]::GetEnvironmentVariable($needVar); if (-not $ans) { $ans = "n (unattended runs never do this without $needVar=y)" } } Say "$q [y/N] $ans (AUTOMATIC ANSWER)" return ($ans -match '^[Yy]') } $a = Read-Host "$q [y/N]" if ($S.report) { try { Add-Content -LiteralPath $S.report -Value "$q [y/N] $a" -Encoding UTF8 -ErrorAction Stop } catch {} } return ($a -match '^\s*(y|yes)\s*$') } function Test-Reparse($p) { try { $i = Get-Item -LiteralPath $p -Force -ErrorAction Stop; return [bool]($i.Attributes -band [IO.FileAttributes]::ReparsePoint) } catch { return $false } } # -- manifests: JSON, UTF-8, one per run. Restored entries are taken out again. -- function Save-Manifest($path, $list) { if (@($list).Count -eq 0) { if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }; return } $dir = Split-Path -Parent $path if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } $json = ConvertTo-Json -InputObject @($list) -Depth 6 Set-Content -LiteralPath $path -Value $json -Encoding UTF8 } function Load-Manifest($path) { $out = @() try { $j = Get-Content -LiteralPath $path -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json; foreach ($c in $j) { if ($c) { $out += $c } } } catch {} return ,$out } function Record($scope, $entry) { $entry.id = [guid]::NewGuid().ToString("N") if ($scope -eq "user") { [void]$S.uchanges.Add($entry); Save-Manifest $S.uman $S.uchanges } else { [void]$S.mchanges.Add($entry); Save-Manifest $S.mman $S.mchanges } } # -- the administrators-only folder: computer-wide undo records and the Safety Scanner download live here -- function Test-AdminOnlyDir($p) { try { $di = Get-Item -LiteralPath $p -Force -ErrorAction Stop if (-not $di.PSIsContainer -or ($di.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return $false } $acl = Get-Acl -LiteralPath $p -ErrorAction Stop $ok = @("S-1-5-32-544", "S-1-5-18") if ($ok -notcontains $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value) { return $false } if (-not $acl.AreAccessRulesProtected) { return $false } foreach ($r in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { if ("$($r.AccessControlType)" -eq "Allow" -and ($ok -notcontains $r.IdentityReference.Value)) { return $false } } return $true } catch { return $false } } function Initialize-AdminRoot { try { if (-not (Test-Path -LiteralPath $AdminRoot)) { New-Item -ItemType Directory -Path $AdminRoot -ErrorAction Stop | Out-Null $acl = New-Object Security.AccessControl.DirectorySecurity $acl.SetAccessRuleProtection($true, $false) foreach ($sid in @("S-1-5-32-544", "S-1-5-18")) { $id = New-Object Security.Principal.SecurityIdentifier $sid $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($id, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"))) } try { Set-Acl -LiteralPath $AdminRoot -AclObject $acl -ErrorAction Stop } catch { $a2 = Get-Acl -LiteralPath $AdminRoot -ErrorAction Stop $a2.SetAccessRuleProtection($true, $false) foreach ($r in @($a2.Access)) { [void]$a2.RemoveAccessRule($r) } foreach ($r in @($acl.Access)) { $a2.AddAccessRule($r) } Set-Acl -LiteralPath $AdminRoot -AclObject $a2 -ErrorAction Stop } $a3 = Get-Acl -LiteralPath $AdminRoot -ErrorAction Stop if (@("S-1-5-32-544", "S-1-5-18") -notcontains $a3.GetOwner([Security.Principal.SecurityIdentifier]).Value) { $a3.SetOwner((New-Object Security.Principal.SecurityIdentifier "S-1-5-32-544")); Set-Acl -LiteralPath $AdminRoot -AclObject $a3 -ErrorAction Stop } if (@(Get-ChildItem -LiteralPath $AdminRoot -Force -ErrorAction SilentlyContinue).Count -gt 0) { return $false } # something slipped in before the lock } } catch { return $false } return (Test-AdminOnlyDir $AdminRoot) } function Test-MicrosoftSigned($path) { try { $sig = Get-AuthenticodeSignature -LiteralPath $path -ErrorAction Stop if ("$($sig.Status)" -ne "Valid" -or -not $sig.SignerCertificate) { return $false } if ($sig.SignerCertificate.Subject -notmatch '(^|,\s*)CN=Microsoft Corporation(,|$)') { return $false } $chain = New-Object Security.Cryptography.X509Certificates.X509Chain $chain.ChainPolicy.RevocationMode = [Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck [void]$chain.Build($sig.SignerCertificate) if ($chain.ChainElements.Count -lt 2) { return $false } $root = $chain.ChainElements[$chain.ChainElements.Count - 1].Certificate return ($root.Subject -match 'CN=Microsoft Root Certificate Authority') } catch { return $false } } function Test-Signed($path) { try { return ("$((Get-AuthenticodeSignature -LiteralPath $path -ErrorAction Stop).Status)" -eq "Valid") } catch { return $false } } # the program of a command line: quoted path, or the longest space-joined prefix that is a real file function Resolve-Exe($val) { $v = [Environment]::ExpandEnvironmentVariables([string]$val).Trim() if ($v -match '^"([^"]+)"') { return $Matches[1] } $parts = @($v -split ' ') for ($i = 0; $i -lt $parts.Count; $i++) { $cand = ($parts[0..$i] -join ' ') if ($cand -notmatch '^([A-Za-z]:\\|\\\\)') { break } foreach ($c in @($cand, "$cand.exe")) { try { if (Test-Path -LiteralPath $c -PathType Leaf) { return $c } } catch {} } } return $parts[0] } $HostRx = '(?i)(^|[\\/"\s])(powershell|pwsh|mshta|wscript|cscript|cmd|rundll32|regsvr32|bitsadmin|certutil)(\.exe)?(["\s]|$)' # -enc must be a whole parameter (-e/-ec/-enc/-encodedcommand) followed by a base64 blob, so "-encoding utf8" is not it; \.js\b does not match .json $EncRx = '(?i)\s[-/]e(c|nc|nco|ncod|ncode|ncoded|ncodedc[a-z]*)?\s+[A-Za-z0-9+/=]{16,}' $CodeRx = '(?i)(FromBase64String|https?://|DownloadString|DownloadFile|Invoke-WebRequest|Invoke-Expression|\biex\b|\birm\b|\biwr\b|\.vbs\b|\.vbe\b|\.jse?\b|\.hta\b|\.wsf\b|vbscript:|javascript:|-urlcache)' $BadLocRx = '(?i)\\(Temp|Tmp)\\|\\Users\\Public\\|\\Downloads\\|\\\$Recycle\.Bin\\|^[A-Za-z]:\\ProgramData\\[^\\]+$' function Quarantine-File($scope, $path, $why) { $S.lastOk = $false $dir = if ($scope -eq "user") { Join-Path $UQ "files" } else { Join-Path $MQ "files" } if ($scope -ne "user" -and -not $S.mtrust) { Say " not moved - no protected folder to keep it in" "Yellow"; return } try { if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } $dest = Join-Path $dir ([guid]::NewGuid().ToString("N") + ".quarantined") # the original name and place live only in the manifest Move-Item -LiteralPath $path -Destination $dest -ErrorAction Stop if ((Test-Path -LiteralPath $path) -or -not (Test-Path -LiteralPath $dest)) { throw "the file did not move" } Record $scope @{ kind = "file"; orig = $path; dest = $dest; why = $why } $S.lastOk = $true; Say " OK moved to quarantine: $path" "Green" } catch { Say " could not move $path : $($_.Exception.Message)" "Red" } } # -- start-up entries in the registry -- function Check-RunKeys($keys, $scope) { $n = 0 foreach ($k in $keys) { $rk = $null; try { $rk = Get-Item -LiteralPath $k -ErrorAction Stop } catch { continue } foreach ($name in @($rk.GetValueNames())) { if (-not $name) { continue } $raw = $rk.GetValue($name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) $vtype = "$($rk.GetValueKind($name))" if ($vtype -ne "String" -and $vtype -ne "ExpandString") { continue } $val = [Environment]::ExpandEnvironmentVariables([string]$raw) $exe = Resolve-Exe $val $rooted = $exe -match '^([A-Za-z]:\\|\\\\)' $exists = $false; if ($rooted) { try { $exists = Test-Path -LiteralPath $exe -PathType Leaf } catch {} } $signed = $exists -and (Test-Signed $exe) $scripty = ($val -match $HostRx) -and (($val -match $EncRx) -or ($val -match $CodeRx)) $badLoc = $exe -match $BadLocRx $reason = $null if ($k -match 'RunOnce$' -and -not ($val -match $EncRx)) { continue } # installers finish their work through RunOnce if ($scripty) { $reason = "it starts a script host (PowerShell, wscript, mshta...) with code or a web address on its command line" } elseif ($exists -and -not $signed -and $badLoc) { $reason = "an unsigned program in a temporary, public or downloads folder" } elseif ($rooted -and -not $exists) { $n++; $S.review++; Say " . review: '$name' points at a program that is no longer there (a leftover; harmless): $val"; continue } else { continue } $n++; $S.susp++ Say " ? looks suspicious: '$name' starts with Windows - $reason" "Red" Say " $val" Say " This is a pattern match, not proof. Company login scripts and developer tools can look like this." if ($scope -ne "user" -and -not $S.mtrust) { Say " not changed - no protected folder to record the change for undo" "Yellow"; continue } if (Ask " Stop it from starting with Windows? (only this start-up entry is removed; -Restore puts it back)") { try { Remove-ItemProperty -LiteralPath $k -Name $name -ErrorAction Stop if ($null -ne (Get-Item -LiteralPath $k).GetValue($name, $null)) { throw "the entry is still there" } Record $scope @{ kind = "regvalue"; orig = "$k\$name"; key = $k; name = $name; value = [string]$raw; vtype = $vtype; why = "start-up entry removed" } $S.fixed++; Say " OK it will no longer start" "Green" if ($exists -and -not $signed -and $badLoc) { if (Ask " Also move its program to quarantine? $exe") { Quarantine-File $scope $exe "program of start-up entry $name" } } } catch { Say " could not remove it: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } } $S.cnt += $n } # -- Startup folders: only unsigned scripts that download or decode something are questioned; shortcuts are listed -- function Check-StartupFolder($d, $scope) { $n = 0 if (-not $d -or -not (Test-Path -LiteralPath $d)) { return } foreach ($f in @(Get-ChildItem -LiteralPath $d -File -Force -ErrorAction SilentlyContinue)) { if ($f.Extension -match '^\.(vbs|vbe|js|jse|wsf|wsh|hta|bat|cmd|ps1|scr|pif)$') { if (Test-Signed $f.FullName) { continue } $text = ""; if ($f.Length -lt 1MB) { try { $text = [IO.File]::ReadAllText($f.FullName) } catch {} } $dl = (($text -match '(?i)(https?|ftp)://') -and ($text -match '(?i)(curl|wget|bitsadmin|certutil|Invoke-WebRequest|DownloadString|DownloadFile|Start-BitsTransfer|XMLHTTP|WinHttpRequest|\biwr\b|\birm\b)')) -or ($text -match '(?i)FromBase64String') -or ($text -match $EncRx) if (-not $dl) { $n++; $S.review++; Say " . review: a script starts with Windows (nothing download-like in it): $($f.FullName)"; continue } $n++; $S.susp++ Say " ? looks suspicious: an unsigned script that downloads or decodes code starts with Windows:" "Red" Say " $($f.FullName)" Say " This is a pattern match, not proof." if (Ask " Move this one file to quarantine? (-Restore puts it back)") { Quarantine-File $scope $f.FullName "start-up script"; if ($S.lastOk) { $S.fixed++ } } else { Say " left as it is" } } elseif ($f.Extension -eq ".lnk") { try { $sc = (New-Object -ComObject WScript.Shell).CreateShortcut($f.FullName) $t = [string]$sc.TargetPath; $a = [string]$sc.Arguments $odd = (-not $t) -or (-not (Test-Path -LiteralPath $t)) -or ("$t $a" -match $HostRx) -or (-not (Test-Signed $t)) if ($odd) { $n++; $S.review++; Say " . review: start-up shortcut '$($f.Name)' runs: $t $a" } } catch {} } } $S.cnt += $n } # ================= part 1: your own account (no administrator rights needed) ================= $IS = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" $UserRunKeys = @("HKCU:\Software\Microsoft\Windows\CurrentVersion\Run", "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce") $MachineRunKeys = @("HKLM:\Software\Microsoft\Windows\CurrentVersion\Run", "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce", "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run", "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce") function User-Checks { Hdr "1 - Your account: web proxy" $px = Get-ItemProperty -LiteralPath $IS -ErrorAction SilentlyContinue $any = $false if ($px -and $px.ProxyEnable -eq 1 -and $px.ProxyServer) { $any = $true; $S.review++; $server = [string]$px.ProxyServer Say " ? This account's web traffic goes through a proxy: $server" "Yellow" if ($server -match '(^|=|/)(127\.0\.0\.1|localhost|\[::1\]):(\d+)') { $port = [int]$Matches[3]; $who = $null try { $l = Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction Stop | Select-Object -First 1; if ($l) { $who = (Get-Process -Id $l.OwningProcess -ErrorAction Stop).ProcessName } } catch {} if ($who) { Say " It points at this PC itself, where the program '$who' is listening - VPNs, filters and developer tools do this." } else { Say " It points at this PC itself, but nothing is listening there, so web pages may fail to load. Often a leftover of removed software." } } else { Say " Normal at work or school and with some VPN or filter software. If you did not set it up, whoever runs that address can see and change the pages you load." } if (Ask " Switch this proxy off? (the address is kept; -Restore switches it back on)" "SHIELD_ANSWER_PROXY") { try { Set-ItemProperty -LiteralPath $IS -Name ProxyEnable -Value 0 -Type DWord -ErrorAction Stop if ((Get-ItemProperty -LiteralPath $IS).ProxyEnable -ne 0) { throw "the setting did not change" } Record "user" @{ kind = "proxy"; orig = "web proxy $server"; why = "proxy switched off" } $S.fixed++; Say " OK switched off" "Green" } catch { Say " could not switch it off: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } if ($px -and $px.AutoConfigURL) { $any = $true; $S.review++; $pac = [string]$px.AutoConfigURL Say " ? This account uses an automatic proxy script: $pac" "Yellow" Say " Normal at work or school. If you did not set it up, that script decides where your web traffic goes." if (Ask " Remove this proxy script setting? (-Restore puts it back)" "SHIELD_ANSWER_PROXY") { try { Remove-ItemProperty -LiteralPath $IS -Name AutoConfigURL -ErrorAction Stop if ((Get-ItemProperty -LiteralPath $IS).AutoConfigURL) { throw "the setting did not change" } Record "user" @{ kind = "pac"; orig = "proxy script $pac"; value = $pac; why = "proxy script removed" } $S.fixed++; Say " OK removed" "Green" } catch { Say " could not remove it: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } $pol = Get-ItemProperty -LiteralPath "HKCU:\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue if ($pol -and ($pol.ProxyServer -or $pol.AutoConfigURL)) { $any = $true; $S.review++; Say " . review: a proxy is set for this account by policy (usual on work PCs): $($pol.ProxyServer) $($pol.AutoConfigURL)" } if (-not $any) { Say " No proxy is set for this account." } Hdr "2 - Your account: programs that start with Windows" $S.cnt = 0 Check-RunKeys $UserRunKeys "user" Check-StartupFolder ([Environment]::GetFolderPath("Startup")) "user" if ($S.cnt -eq 0) { Say " Nothing obviously suspicious in the places we checked (this account's Run keys and Startup folder)." } } # ================= part 2: the whole computer (administrator) ================= $KnownHosts = @("microsoft.com","windowsupdate.com","windows.com","live.com","office.com","microsoftonline.com","msftncsi.com","google.com","googleapis.com", "gstatic.com","gmail.com","youtube.com","bing.com","apple.com","icloud.com","facebook.com","amazon.com","paypal.com","chase.com","bankofamerica.com", "wellsfargo.com","citi.com","capitalone.com","usbank.com","americanexpress.com","malwarebytes.com","avast.com","avg.com","norton.com","symantec.com", "mcafee.com","kaspersky.com","bitdefender.com","eset.com","sophos.com","trendmicro.com","virustotal.com","f-secure.com") function Test-KnownHost($h) { $h = ([string]$h).ToLower().TrimEnd('.'); foreach ($k in $KnownHosts) { if ($h -eq $k -or $h.EndsWith(".$k")) { return $true } }; return $false } # hosts lines that name a well-known site (whole host names only): "redirect" = sent to another address, "block" = sent nowhere function Read-HostsHits($path) { $hits = @() $lines = @(); try { $lines = [IO.File]::ReadAllLines($path, [Text.Encoding]::Default) } catch { return ,$hits } foreach ($line in $lines) { $t = ($line -replace '#.*$', '').Trim(); if (-not $t) { continue } $tok = @($t -split '\s+'); if ($tok.Count -lt 2) { continue } $names = @($tok[1..($tok.Count - 1)] | Where-Object { Test-KnownHost $_ }); if ($names.Count -eq 0) { continue } $kind = if ($tok[0] -match '^(0\.0\.0\.0|127\.\d+\.\d+\.\d+|::1?|0:0:0:0:0:0:0:[01])$') { "block" } else { "redirect" } $hits += New-Object PSObject -Property @{ line = $line; kind = $kind } } return ,$hits } function Test-SuspiciousExclusion($type, $v) { $x = [Environment]::ExpandEnvironmentVariables([string]$v).Trim() if ($type -eq "Extension") { return (($x.TrimStart('*').TrimStart('.')) -match '^(?i)(exe|dll|sys|ps1|bat|cmd|vbs|vbe|js|jse|wsf|hta|scr|com|msi|jar|lnk|\*)$') } if ($type -eq "Process" -and $x -notmatch '\\') { return ($x -match '^(?i)(\*|powershell\.exe|pwsh\.exe|cmd\.exe|wscript\.exe|cscript\.exe|mshta\.exe|rundll32\.exe|regsvr32\.exe)$') } return ($x -match '(?i)^[A-Za-z]:\\?\*?$|\\(Temp|Tmp)(\\|$)|\\AppData(\\|$)|\\Downloads(\\|$)|\\Users\\Public(\\|$)|^[A-Za-z]:\\Users(\\[^\\]+)?\\?\*?$|^[A-Za-z]:\\ProgramData\\?\*?$|^[A-Za-z]:\\Windows\\?\*?$') } function Machine-Checks { # ---- hosts + system proxy first: they decide where the downloads further down really come from ---- Hdr "3 - Hosts file and system-wide proxy" $defDir = Join-Path $env:SystemRoot "System32\drivers\etc" $hosts = Join-Path $defDir "hosts" $tcp = Get-ItemProperty -LiteralPath "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" -ErrorAction SilentlyContinue if ($tcp -and $tcp.DataBasePath) { $dbDir = [Environment]::ExpandEnvironmentVariables([string]$tcp.DataBasePath).TrimEnd('\') if ($dbDir -ne $defDir) { $S.susp++ Say " ? looks suspicious: Windows is told to read its hosts file from an unusual folder: $dbDir" "Red" Say " (normal is $defDir). Malware does this to hide a second hosts file. Not changed - the setting is" Say " HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath; ask someone you trust before editing it." $alt = Join-Path $dbDir "hosts" foreach ($h in (Read-HostsHits $alt)) { if ($h.kind -eq "redirect") { Say " that file redirects: $($h.line)" "Red" } } } } $hits = Read-HostsHits $hosts $blocks = @($hits | Where-Object { $_.kind -eq "block" }); $redir = @($hits | Where-Object { $_.kind -eq "redirect" }) if ($blocks.Count) { $S.review++ Say " . review: $($blocks.Count) hosts line(s) BLOCK well-known sites (send them nowhere). Probably an ad-blocker or privacy tool; not changed:" $blocks | Select-Object -First 8 | ForEach-Object { Say " $($_.line)" } } if ($redir.Count) { $S.susp++ Say " ? looks suspicious: the hosts file sends well-known sites to another address:" "Red" $redir | ForEach-Object { Say " $($_.line)" } Say " Unless you or your IT added these on purpose, they make those sites open somewhere else." if (-not $S.mtrust) { Say " not changed - no protected folder to record the change for undo" "Yellow" } elseif (Ask " Remove only these $($redir.Count) line(s) from the hosts file? (a full copy is kept; -Restore adds the lines back)") { try { if (-not (Test-Path -LiteralPath $MQ)) { New-Item -ItemType Directory -Force -Path $MQ | Out-Null } $bk = Join-Path $MQ "hosts.before" Copy-Item -LiteralPath $hosts -Destination $bk -Force -ErrorAction Stop $bad = @($redir | ForEach-Object { $_.line }) $all = [IO.File]::ReadAllLines($hosts, [Text.Encoding]::Default) $keep = @($all | Where-Object { $bad -notcontains $_ }) [IO.File]::WriteAllLines($hosts, [string[]]$keep, [Text.Encoding]::Default) if (@(Read-HostsHits $hosts | Where-Object { $_.kind -eq "redirect" }).Count -ne 0) { throw "the lines are still there" } Record "machine" @{ kind = "hostslines"; orig = "$($bad.Count) hosts line(s)"; lines = $bad; backup = $bk; why = "redirecting hosts lines removed" } $S.fixed++; Say " OK those lines were removed (copy of the old file: $bk)" "Green" } catch { Say " could not change the hosts file: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } if (-not $blocks.Count -and -not $redir.Count) { Say " The hosts file does not redirect or block the well-known sites we look for." } try { $w = (& (Join-Path $env:SystemRoot "System32\netsh.exe") winhttp show proxy 2>$null | Out-String) if ($w -match '(?m):\s*(\S+:\d+\S*)\s*$') { $S.review++; Say " . review: Windows services use a proxy (WinHTTP): $($Matches[1]) - normal on some work PCs; to clear: netsh winhttp reset proxy" } } catch {} $mpol = Get-ItemProperty -LiteralPath "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" -ErrorAction SilentlyContinue if ($mpol -and ($mpol.ProxyServer -or $mpol.AutoConfigURL -or $null -ne $mpol.ProxySettingsPerUser)) { $S.review++; Say " . review: proxy settings are set for the whole PC by policy (usual on work PCs): $($mpol.ProxyServer) $($mpol.AutoConfigURL)" } # ---- antivirus state ---- Hdr "4 - Antivirus state" $mp = $null; try { $mp = Get-MpComputerStatus -ErrorAction Stop } catch {} $third = @(); try { $third = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction Stop | Where-Object { $_.displayName -notmatch 'Windows Defender|Microsoft Defender' }) } catch {} $tn = (@($third | ForEach-Object { $_.displayName }) | Select-Object -Unique) -join ", " $defenderOk = $false; $S.defenderOk = $false if (-not $mp) { if ($third.Count) { Say " Microsoft Defender is not answering; another antivirus is registered with Windows: $tn. That is normal." } else { $S.review++; Say " Microsoft Defender is not answering and no other antivirus is registered with Windows. Open Windows Security to see why." "Yellow" } } else { $mode = [string]$mp.AMRunningMode if ($mode -match 'Passive' -or (-not $mp.AntivirusEnabled -and $third.Count)) { Say " Another antivirus ($tn) protects this PC and Microsoft Defender is standing by (mode: $mode). That is normal, not a sign of a virus." } elseif (-not $mp.AMServiceEnabled -or -not $mp.AntivirusEnabled) { $S.susp++ Say " ? Microsoft Defender is OFF and no other antivirus is registered with Windows." "Red" Say " That can be a setting, a company policy, or malware. Switch it on in Windows Security > Virus & threat protection." } else { $defenderOk = $true; $S.defenderOk = $true if (-not $mp.RealTimeProtectionEnabled) { $S.review++ Say " ? Defender's real-time protection is OFF (files are not checked as they arrive)." "Yellow" Say " People and installers switch this off on purpose sometimes; malware does too." if (-not $S.mtrust) { Say " not changed - no protected folder to record the change for undo" "Yellow" } elseif (Ask " Switch real-time protection on? (-Restore can switch it back off)") { try { Set-MpPreference -DisableRealtimeMonitoring $false -ErrorAction Stop $on = $false; for ($i = 0; $i -lt 10 -and -not $on; $i++) { Start-Sleep -Seconds 1; $on = [bool](Get-MpComputerStatus).RealTimeProtectionEnabled } if (-not $on) { throw "Windows accepted the request but protection is still off (tamper protection or a policy holds it)" } Record "machine" @{ kind = "realtime"; orig = "real-time protection (was off)"; why = "real-time protection switched on" } $S.fixed++; Say " OK real-time protection is on" "Green" } catch { Say " could not switch it on: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } else { Say " Microsoft Defender is on with real-time protection." } } try { $pref = Get-MpPreference -ErrorAction Stop foreach ($set in @(@("Path", $pref.ExclusionPath), @("Process", $pref.ExclusionProcess), @("Extension", $pref.ExclusionExtension))) { $type = $set[0] foreach ($ex in @($set[1])) { if (-not $ex -or "$ex" -match '^N/A') { continue } if (-not (Test-SuspiciousExclusion $type $ex)) { $S.review++; Say " . review: Defender skips this $($type.ToLower()): $ex (keep it if you or your software added it)"; continue } $S.susp++ Say " ? looks suspicious: Defender is told to skip the $($type.ToLower()) '$ex'" "Red" Say " That covers a place or file type where malware usually lives, so nothing there is scanned." if (-not $S.mtrust) { Say " not changed - no protected folder to record the change for undo" "Yellow"; continue } if (Ask " Remove this exclusion? (-Restore puts it back)") { try { $p = @{ ErrorAction = "Stop" }; $p["Exclusion$type"] = [string]$ex Remove-MpPreference @p if (@((Get-MpPreference)."Exclusion$type") -contains $ex) { throw "the exclusion is still there" } Record "machine" @{ kind = "exclusion"; orig = "Defender $($type.ToLower()) exclusion $ex"; xtype = $type; value = [string]$ex; why = "Defender exclusion removed" } $S.fixed++; Say " OK removed" "Green" } catch { Say " could not remove it: $($_.Exception.Message)" "Red" } } else { Say " left as it is" } } } } catch { Say " . Defender's exclusion list could not be read: $($_.Exception.Message)" } } # ---- computer-wide start-up ---- Hdr "5 - The computer: programs that start with Windows" $S.cnt = 0 Check-RunKeys $MachineRunKeys "machine" Check-StartupFolder ([Environment]::GetFolderPath("CommonStartup")) "machine" if ($S.cnt -eq 0) { Say " Nothing obviously suspicious in the places we checked (computer-wide Run keys and Startup folder)." } Say " Listed for review only (nothing here is changed) - made in the last 30 days, not by Microsoft:" $cut = (Get-Date).AddDays(-30); $listed = 0 try { foreach ($t in @(Get-ScheduledTask -ErrorAction Stop)) { if ($t.TaskPath -like '\Microsoft\*' -or "$($t.Author)" -match 'Microsoft') { continue } $d = $null; try { $d = [datetime]$t.Date } catch {} if (-not $d -or $d -lt $cut) { continue } $act = (@($t.Actions | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join " ; ") if ($listed -lt 25) { Say " task $($t.TaskPath)$($t.TaskName) -> $act" }; $listed++; $S.review++ } } catch { Say " (scheduled tasks could not be listed)" } try { foreach ($e in @(Get-WinEvent -FilterHashtable @{ LogName = "System"; Id = 7045; StartTime = $cut } -ErrorAction Stop)) { $img = [string]$e.Properties[1].Value $norm = $img -replace '^\\SystemRoot\\', "$env:SystemRoot\" -replace '^\\\?\?\\', '' -replace '^(?i)system32\\', "$env:SystemRoot\System32\" $x = Resolve-Exe $norm; $who = "file not found" if ($x -match '^[A-Za-z]:\\' -and (Test-Path -LiteralPath $x -PathType Leaf)) { if (Test-MicrosoftSigned $x) { continue } $who = "unsigned"; try { $sg = Get-AuthenticodeSignature -LiteralPath $x; if ("$($sg.Status)" -eq "Valid" -and $sg.SignerCertificate.Subject -match 'CN=([^,]+)') { $who = "signed by " + $Matches[1].Trim('"') } } catch {} } if ($listed -lt 25) { Say " service $($e.Properties[0].Value) -> $img ($who)" }; $listed++; $S.review++ } } catch {} foreach ($cls in @("CommandLineEventConsumer", "ActiveScriptEventConsumer")) { try { foreach ($c in @(Get-CimInstance -Namespace root/subscription -ClassName $cls -ErrorAction Stop)) { $body = "$($c.CommandLineTemplate)$($c.ScriptText)"; if ($body.Length -gt 200) { $body = $body.Substring(0, 200) + "..." } Say " WMI subscription ($cls) $($c.Name) -> $body"; $listed++; $S.review++ } } catch {} } if ($listed -eq 0) { Say " none" } elseif ($listed -gt 25) { Say " ... and $($listed - 25) more" } # ---- the scanner ---- if ($defenderOk) { Hdr "6 - Microsoft Defender scan" $scanStart = Get-Date Say " Updating the virus list..." try { Update-MpSignature -ErrorAction Stop; Say " OK virus list updated" "Green" } catch { Say " could not update the virus list: $($_.Exception.Message)" "Yellow"; Say " scanning with the list already on this PC" } $type = if ($Full) { "FullScan" } else { "QuickScan" } $label = "Microsoft Defender ($(if ($Full) {'full'} else {'quick'}) scan" $skips = @(); try { $pp = Get-MpPreference -ErrorAction Stop; $skips = @(@($pp.ExclusionPath) + @($pp.ExclusionProcess) + @($pp.ExclusionExtension) | Where-Object { $_ -and "$_" -notmatch '^N/A' }) } catch {} if ($skips.Count) { Say " Note: Defender is still told to skip these, so this scan does NOT look at them: $($skips -join ', ')" "Yellow" $label += "; it skipped the excluded: $($skips -join ', ')" } $label += ")" Say " Running a $(if ($Full) {'FULL scan (can take an hour or more)'} else {'quick scan (a few minutes)'})..." $scanErr = $null; try { Start-MpScan -ScanType $type -ErrorAction Stop } catch { $scanErr = $_.Exception.Message } # only what THIS scan found, plus anything Defender still lists as active - not the PC's whole detection history $ids = @() try { $ids += @(Get-MpThreatDetection -ErrorAction Stop | Where-Object { $_.InitialDetectionTime -and $_.InitialDetectionTime.ToUniversalTime() -ge $scanStart.ToUniversalTime() } | ForEach-Object { $_.ThreatID }) } catch {} try { $ids += @(Get-MpThreat -ErrorAction Stop | Where-Object { $_.IsActive } | ForEach-Object { $_.ThreatID }) } catch {} $ids = @($ids | Where-Object { $_ } | Select-Object -Unique) if ($scanErr) { Say " The scan did not finish: $scanErr" "Red"; $S.notrun += "Microsoft Defender scan (error: $scanErr)" } if ($ids.Count -eq 0) { if (-not $scanErr) { Say " Microsoft Defender's $(if ($Full) {'full'} else {'quick'}) scan found nothing$(if ($skips.Count) {' in the places it was allowed to look'})."; $S.okby += $label } } else { foreach ($id in $ids) { $S.found++; $t = $null; try { $t = Get-MpThreat -ThreatID $id -ErrorAction Stop } catch {} Say " ! Microsoft Defender: $(if ($t) { $t.ThreatName } else { "threat $id" })" "Red" if ($t) { foreach ($r in @($t.Resources)) { Say " $r" } } } if (Ask " Let Microsoft Defender remove these $($ids.Count) item(s)? (they go to Defender's own quarantine; Windows Security > Protection history can restore them)") { try { Remove-MpThreat -ErrorAction Stop } catch { Say " Defender reported a problem while removing: $($_.Exception.Message)" "Red" } Start-Sleep -Seconds 3 $still = @(); try { $still = @(Get-MpThreat -ErrorAction Stop | Where-Object { $_.IsActive -and ($ids -contains $_.ThreatID) }) } catch {} $gone = $ids.Count - $still.Count; $S.removed += $gone if ($still.Count) { Say " Defender reports $gone of $($ids.Count) dealt with; still active: $(@($still | ForEach-Object { $_.ThreatName }) -join ', '). A restart or the offline scan below may be needed." "Red" } else { Say " OK Defender reports none of them active any more" "Green" } } else { Say " left to Defender's own handling - see Windows Security > Protection history" } } } else { # Microsoft Safety Scanner: only when Defender is not the working antivirus, and only if you say yes Hdr "6 - Microsoft Safety Scanner" Say " Microsoft Defender is not the active antivirus here, so its scan was not run." $S.notrun += "Microsoft Defender scan (Defender is not active on this PC)" if (-not $S.mtrust) { Say " Safety Scanner not run - no protected folder to download it into." "Yellow"; $S.notrun += "Microsoft Safety Scanner (no protected folder)" } elseif (-not (Ask " Download Microsoft Safety Scanner from microsoft.com (about 200 MB) and run it? It removes what it finds by itself and lists every change in its log.")) { $S.notrun += "Microsoft Safety Scanner (you chose not to)" } else { $exe = Join-Path $AdminRoot "msert_$Stamp.exe" # administrators-only folder: nobody else can swap the file before it runs $url = if ([Environment]::Is64BitOperatingSystem) { "https://go.microsoft.com/fwlink/?LinkId=212732" } else { "https://go.microsoft.com/fwlink/?LinkId=212733" } try { Say " Downloading..." Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $exe -ErrorAction Stop $log = Join-Path $env:SystemRoot "debug\msert.log"; $t0 = Get-Date if (-not (Test-MicrosoftSigned $exe)) { $S.susp++; $S.notrun += "Microsoft Safety Scanner (download was not signed by Microsoft)" Say " ! The download is NOT signed by Microsoft Corporation - deleted, not run. Something on this PC or network changes downloads." "Red" } else { Say " Signed by Microsoft Corporation. Scanning$(if ($Full) {' everything (can take hours)'})... the window may look still; it is working." $a = if ($Full) { @("/Q", "/F:Y") } else { @("/Q") } $p = Start-Process -FilePath $exe -ArgumentList $a -PassThru -Wait -ErrorAction Stop $code = $p.ExitCode # this run's part of the log only (the file is appended to on every run) $sec = @() if ((Test-Path -LiteralPath $log) -and (Get-Item -LiteralPath $log).LastWriteTime -ge $t0) { $all = @(Get-Content -LiteralPath $log); $start = 0 for ($i = $all.Count - 1; $i -ge 0; $i--) { if ($all[$i] -match 'Started On') { $start = $i; break } } $sec = @($all[$start..($all.Count - 1)] | Where-Object { $_ -match '(?i)threat|infect|found|remov|result|return code|action' }) } # exit codes as documented for Microsoft's removal tools: 0 nothing found; 6-7 found; 8-13 found and removed; others = it could not run properly if ($code -eq 0) { Say " Microsoft Safety Scanner finished and reports no infection (exit code 0)."; $S.okby += "Microsoft Safety Scanner" } elseif ($code -ge 6 -and $code -le 13) { $S.found++ if ($code -ge 8) { $S.removed++; Say " ! Microsoft Safety Scanner reports it found and removed an infection (exit code $code). A restart may be needed." "Red" } else { Say " ! Microsoft Safety Scanner reports an infection it did not fully remove (exit code $code)." "Red" } } else { Say " Microsoft Safety Scanner did not complete (exit code $code)." "Yellow"; $S.notrun += "Microsoft Safety Scanner (exit code $code)" } if ($sec.Count) { Say " From its log ($log):"; $sec | Select-Object -First 20 | ForEach-Object { Say " $_" } } } } catch { Say " Safety Scanner could not be downloaded or started: $($_.Exception.Message)" "Red"; $S.notrun += "Microsoft Safety Scanner (error: $($_.Exception.Message))" } finally { Remove-Item -LiteralPath $exe -Force -ErrorAction SilentlyContinue } } } } # ================= restore ================= # Every entry is checked against what this script can have written: known kinds, known registry keys, known places. function Restore-Entry($c, $scope, $mdir) { $S.lastOk = $false $kinds = if ($scope -eq "user") { @("regvalue", "proxy", "pac", "file") } else { @("regvalue", "exclusion", "realtime", "hostslines", "file") } if ($kinds -notcontains [string]$c.kind) { Say " . skipped an entry this version does not handle ($($c.kind))"; return } try { switch ([string]$c.kind) { "regvalue" { $allowed = if ($scope -eq "user") { $UserRunKeys } else { $MachineRunKeys } if ($allowed -notcontains [string]$c.key -or @("String", "ExpandString") -notcontains [string]$c.vtype -or -not $c.name) { Say " . skipped (not a start-up entry of ours): $($c.key)"; return } Say " Start-up entry '$($c.name)' in $($c.key), running: $($c.value)" if (-not (Test-Path -LiteralPath $c.key)) { New-Item -Path $c.key -Force | Out-Null } if ($null -ne (Get-Item -LiteralPath $c.key).GetValue([string]$c.name, $null)) { Say " an entry with that name exists again - left alone"; return } if (-not (Ask " Put this start-up entry back?")) { return } New-ItemProperty -LiteralPath $c.key -Name ([string]$c.name) -Value ([string]$c.value) -PropertyType ([string]$c.vtype) -Force -ErrorAction Stop | Out-Null if ($null -eq (Get-Item -LiteralPath $c.key).GetValue([string]$c.name, $null)) { throw "the entry did not come back" } } "proxy" { Say " Web proxy of this account ($($c.orig)) - was switched off" if (-not (Ask " Switch the proxy back on?" "SHIELD_ANSWER_PROXY")) { return } Set-ItemProperty -LiteralPath $IS -Name ProxyEnable -Value 1 -Type DWord -ErrorAction Stop if ((Get-ItemProperty -LiteralPath $IS).ProxyEnable -ne 1) { throw "the setting did not change" } } "pac" { if ([string]$c.value -notmatch '^(https?|file)://\S+$') { Say " . skipped (not a proxy script address)"; return } Say " Automatic proxy script: $($c.value) - was removed" if (-not (Ask " Set this proxy script again?" "SHIELD_ANSWER_PROXY")) { return } Set-ItemProperty -LiteralPath $IS -Name AutoConfigURL -Value ([string]$c.value) -Type String -ErrorAction Stop } "exclusion" { if (@("Path", "Process", "Extension") -notcontains [string]$c.xtype -or -not $c.value) { Say " . skipped (not a Defender exclusion of ours)"; return } Say " Defender $(([string]$c.xtype).ToLower()) exclusion: $($c.value) - was removed" if (-not (Ask " Add this Defender exclusion again (Defender will stop scanning it)?")) { return } $p = @{ ErrorAction = "Stop" }; $p["Exclusion$($c.xtype)"] = [string]$c.value Add-MpPreference @p if (@((Get-MpPreference)."Exclusion$($c.xtype)") -notcontains [string]$c.value) { throw "the exclusion did not come back" } } "realtime" { Say " Defender real-time protection - was off before, we switched it on" if (-not (Ask " Switch real-time protection back OFF, as it was?")) { return } Set-MpPreference -DisableRealtimeMonitoring $true -ErrorAction Stop } "hostslines" { $lines = @($c.lines | ForEach-Object { [string]$_ }) foreach ($l in $lines) { if ($l -notmatch '^\s*[0-9A-Fa-f:.]+\s+\S' -or $l -match '[\r\n]') { Say " . skipped (not hosts lines)"; return } } Say " Hosts file lines that were removed:"; $lines | ForEach-Object { Say " $_" } if (-not (Ask " Add these $($lines.Count) line(s) back to the hosts file?")) { return } $hosts = Join-Path $env:SystemRoot "System32\drivers\etc\hosts" $cur = [IO.File]::ReadAllText($hosts, [Text.Encoding]::Default) $add = ($lines -join "`r`n") + "`r`n"; if ($cur.Length -and -not $cur.EndsWith("`n")) { $add = "`r`n" + $add } [IO.File]::AppendAllText($hosts, $add, [Text.Encoding]::Default) } "file" { $orig = [IO.Path]::GetFullPath([string]$c.orig); $dest = [IO.Path]::GetFullPath([string]$c.dest) $home1 = [IO.Path]::GetFullPath((Join-Path $mdir "files")) + "\" if (-not $dest.StartsWith($home1, [StringComparison]::OrdinalIgnoreCase) -or (Test-Reparse $dest) -or -not (Test-Path -LiteralPath $dest -PathType Leaf)) { Say " . skipped (the quarantined file is not where this script put it): $($c.orig)"; return } $okRoot = $false if ($scope -eq "user") { $okRoot = $orig.StartsWith(([IO.Path]::GetFullPath($UserDir) + "\"), [StringComparison]::OrdinalIgnoreCase) -or $orig.StartsWith(([IO.Path]::GetTempPath()), [StringComparison]::OrdinalIgnoreCase) } else { $okRoot = -not ($orig.StartsWith(($env:SystemRoot + "\"), [StringComparison]::OrdinalIgnoreCase) -or $orig -match '(?i)^[A-Za-z]:\\Program Files( \(x86\))?\\') } if (-not $okRoot) { Say " . skipped (this script does not put files there): $orig"; return } Say " File in quarantine: $orig ($($c.why))" if (Test-Path -LiteralPath $orig) { Say " a file is already at that place - left in quarantine"; return } if (-not (Ask " Move this file back to where it was?")) { return } $parent = Split-Path -Parent $orig; if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null } Move-Item -LiteralPath $dest -Destination $orig -ErrorAction Stop if (-not (Test-Path -LiteralPath $orig)) { throw "the file did not move" } } } $S.lastOk = $true; Say " OK put back" "Green" } catch { Say " could not put it back: $($_.Exception.Message)" "Red" } } function Restore-Manifests($root, $scope) { $seen = 0; $done = 0 $qdir = Join-Path $root "quarantine" foreach ($dir in @(Get-ChildItem -LiteralPath $qdir -Directory -ErrorAction SilentlyContinue)) { $m = Join-Path $dir.FullName "manifest.json" if ((Test-Reparse $dir.FullName) -or -not (Test-Path -LiteralPath $m -PathType Leaf) -or (Test-Reparse $m)) { continue } $list = Load-Manifest $m $left = New-Object System.Collections.ArrayList; foreach ($c in $list) { [void]$left.Add($c) } for ($i = $list.Count - 1; $i -ge 0; $i--) { # newest change first $seen++; Restore-Entry $list[$i] $scope $dir.FullName if ($S.lastOk) { $done++; $left.Remove($list[$i]); Save-Manifest $m $left } } } Say " $(if ($scope -eq 'user') {'Your account'} else {'The computer'}): put back $done of $seen recorded change(s)." } function Result-Lines($final) { Hdr "Result" if ($S.found) { Say " Threats named by a Microsoft scanner: $($S.found) (the scanner reports removed: $($S.removed))" "Red" } if ($S.susp) { Say " Settings or start-up items that look suspicious (pattern match, not proof): $($S.susp)" "Yellow" } if ($S.fixed) { Say " Changed at your choice: $($S.fixed)" } if ($S.review) { Say " Things listed above for you to review: $($S.review)" } if ($final) { if ($S.okby.Count) { Say " Nothing found by: $($S.okby -join ', ')." "Green" } if ($S.notrun.Count) { Say " Not run: $($S.notrun -join '; ')." "Yellow" } if (-not $S.okby.Count -and -not $S.found) { Say " No scanner finished a check, so this run cannot tell you whether this PC has malware." "Red" } Say " A scan only knows the malware on its list and only looks where it was pointed. It cannot prove a PC is clean." } if ($S.uchanges.Count -or $S.mchanges.Count) { Say " Changed your mind? Undo our changes (asks about each one): & ([scriptblock]::Create((irm $SELF))) -Restore" } if ($final) { Say " -Restore cannot undo what Microsoft Defender or Safety Scanner removed: see Windows Security > Protection history." Say " Privacy: our script uploads nothing; Microsoft Defender's own cloud sample submission follows this PC's settings." } if ($S.report) { Say " Full report: $($S.report)" } } # ================= run ================= if (-not $MachineOnly) { try { if (-not (Test-Path -LiteralPath $USH)) { New-Item -ItemType Directory -Force -Path $USH | Out-Null } $S.report = Join-Path $USH "cure_$Stamp.txt" } catch {} Say "Providence Shield - CURE $(Get-Date) ($([Environment]::OSVersion.VersionString))" "Yellow" } else { # started by the first window: keep writing the same report in the ORIGINAL user's profile, if that is a plain folder $rp = Join-Path $USH "cure_$Stamp.txt" if ((Test-Path -LiteralPath $USH -PathType Container) -and -not (Test-Reparse $USH) -and -not (Test-Reparse $rp)) { $S.report = $rp } Say "Providence Shield - CURE, administrator part $(Get-Date)" "Yellow" } if ($S.report) { Say " Report: $($S.report)" } if ($env:SHIELD_ANSWER) { Say " ############################################################################" "Red" Say " # UNATTENDED MODE: every question is answered '$($env:SHIELD_ANSWER)' automatically." "Red" Say " # (SHIELD_ANSWER is set. Remove it to be asked about each item.)" "Red" Say " ############################################################################" "Red" } if (-not $MachineOnly) { if ($Restore) { Hdr "Undo - your account"; Restore-Manifests $USH "user" } else { User-Checks } } if (-not $isAdmin) { if (-not $Restore) { Result-Lines $false } Say "" Say "The rest (hosts file, antivirus, the Microsoft scan) needs administrator rights. Windows will ask you now;" "Yellow" Say "it continues in a new window." "Yellow" $q = { param($s) "'" + ([string]$s -replace "'", "''") + "'" } $flags = @("-MachineOnly", "-UserDir", (& $q $UserDir), "-Stamp", (& $q $Stamp)) if ($Restore) { $flags += "-Restore" }; if ($Full) { $flags += "-Full" }; if ($NoOffline) { $flags += "-NoOffline" } $cmd = "[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072; " + "try { & ([scriptblock]::Create((Invoke-RestMethod '$SELF'))) $($flags -join ' ') } catch { Write-Host ('Could not start: ' + `$_.Exception.Message) -ForegroundColor Red }; " + "Read-Host 'Press Enter to close this window'" try { Start-Process -FilePath $PSEXE -Verb RunAs -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", $cmd) -ErrorAction Stop } catch { Say "You declined the administrator prompt (or Windows could not show it): $($_.Exception.Message)" "Red" Say "Not run: hosts file check, antivirus state, computer-wide start-up entries, the Microsoft Defender scan." "Red" Say "No scanner ran, so this run cannot tell you whether this PC has malware. Run it again and choose Yes to do the rest." } return } $S.mtrust = [bool](Initialize-AdminRoot) if (-not $S.mtrust) { Say " ! The folder $AdminRoot exists but is not an administrators-only folder made by this tool." "Red" Say " Computer-wide items will be reported only; nothing computer-wide will be changed or restored. (An administrator can delete that folder and run this again.)" } if ($Restore) { Hdr "Undo - the computer" if ($S.mtrust) { Restore-Manifests $AdminRoot "machine" } else { Say " not done (see above)" } if ($S.report) { Say " Full report: $($S.report)" } return } Machine-Checks $defenderOk = [bool]$S.defenderOk Result-Lines $true if ($defenderOk -and -not $NoOffline -and (Get-Command Start-MpWDOScan -ErrorAction SilentlyContinue)) { Say "" Say " Optional: Microsoft Defender Offline restarts this PC and scans for about 15 minutes BEFORE Windows starts." "Yellow" Say " It can find malware that hides while Windows is running. Save your work first. No USB stick needed." "Yellow" $bl = $null; try { $bl = Get-BitLockerVolume -MountPoint $env:SystemDrive -ErrorAction Stop } catch {} if ($bl -and "$($bl.ProtectionStatus)" -eq "On") { Say " IMPORTANT: this PC's drive is encrypted with BitLocker. After the restart Windows may ask for the BitLocker" "Red" Say " recovery key. Make sure you HAVE that key first (https://account.microsoft.com/devices/recoverykey, or your IT" "Red" Say " department). Without it you may not be able to get back into this PC." "Red" } elseif (-not $bl) { Say " If this PC uses BitLocker or 'device encryption', Windows may ask for the recovery key after the restart -" "Yellow" Say " have it ready first (https://account.microsoft.com/devices/recoverykey)." "Yellow" } if (Ask " Restart now and run the offline scan?") { Say " Restarting into Defender Offline..."; Start-MpWDOScan } } } @args