# ACIDRIPP Threat Analysis Toolkit: scanner for Windows (Windows PowerShell 5.1 or PowerShell 7). # https://cybersecurity.acidripp.com/en/tools/threat-analysis-toolkit/ # Source and issues: https://github.com/MariusVava/acidripp-threat-toolkit # # What it does: compares this machine with what attackers did to ACIDRIPP's own decoys and servers. # 1. services listening for connections, against the ports attackers connect to # 2. Remote Desktop, SSH and account settings attackers rely on # 3. files in temporary folders, against the hashes of captured malware # 4. connections, name lookups and start-up entries that mention the servers captured malware takes orders from # 5. secret files left inside web folders, from the list of files attackers ask websites for # 6. the machine's own logs, against the addresses that attacked us # # What it does not do: it changes nothing, installs nothing, and sends nothing about this machine anywhere. # It makes two downloads from cybersecurity.acidripp.com (the indicator list and the address list) and # writes one report file in the folder you run it from. Run it in a PowerShell window opened with # "Run as administrator" to include the sign-in log; without that it says what it skipped. # # A match is a reason to look, not proof of a break-in. A clean result covers only what we have seen. # Licence: MIT for this script, CC BY 4.0 for the lists. No warranty. [CmdletBinding()] param( [string]$Offline = "", # a folder holding indicators.tsv and addresses.txt: nothing is downloaded [switch]$NoReport # print the result only, write no report file ) $ErrorActionPreference = "SilentlyContinue" $ProgressPreference = "SilentlyContinue" $Version = "1.0.1" $Base = "https://cybersecurity.acidripp.com" $Page = "https://cybersecurity.acidripp.com/en/tools/threat-analysis-toolkit/" $Report = New-Object System.Collections.Generic.List[string] $Count = @{ warn = 0; look = 0; skip = 0 } function Out([string]$Text, [string]$Color = "") { if ($Color) { Write-Host $Text -ForegroundColor $Color } else { Write-Host $Text } $Report.Add($Text) } function Head([string]$t) { Out ""; Out "== $t ==" } function Ok([string]$t) { Out " ok $t" "Green" } function Info([string]$t) { Out " info $t" } function Look([string]$t) { Out " LOOK $t" "Yellow"; $Count.look++ } function Warn([string]$t) { Out " WARN $t" "Red"; $Count.warn++ } function Skip([string]$t) { Out " skip $t" "DarkGray"; $Count.skip++ } function More([string]$t) { Out " $t" } function SeenOn($n) { if ([int]$n -gt 0) { "$n attacker addresses connected to this port on our decoy in the last 30 days." } else { "Attackers look for this service, though none connected to it on our decoy in the last 30 days." } } $IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) Out "ACIDRIPP Threat Analysis Toolkit scanner $Version" Out ("Machine: Windows {0} Started: {1} Administrator rights: {2}" -f [Environment]::OSVersion.Version, (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), $(if ($IsAdmin) { "yes" } else { "no" })) # ---- the lists ----------------------------------------------------------------------------------------- function Fetch([string]$Url) { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $c = New-Object Net.WebClient $c.Headers.Add("User-Agent", "acidripp-scan/$Version") $c.Encoding = [Text.Encoding]::UTF8 return $c.DownloadString($Url) } $IndText = $null; $AddrText = "" if ($Offline) { $IndText = Get-Content -Raw -LiteralPath (Join-Path $Offline "indicators.tsv") $AddrText = Get-Content -Raw -LiteralPath (Join-Path $Offline "addresses.txt") } else { try { $IndText = Fetch "$Base/feed/toolkit/indicators.tsv" } catch { $IndText = $null } try { $AddrText = Fetch "$Base/feed/block/standard.plain" } catch { $AddrText = "" } } if (-not $IndText -or $IndText -notmatch "(?m)^generated`t") { Write-Host "Could not read the indicator list from $Base. Check the connection, or see -Offline." -ForegroundColor Red return } $Rows = @($IndText -split "`r?`n" | Where-Object { $_ -and -not $_.StartsWith("#") } | ForEach-Object { , ($_ -split "`t") }) function Kind([string]$k) { , @($Rows | Where-Object { $_[0] -eq $k }) } $Ports = Kind "port"; $Paths = Kind "path"; $Exploits = Kind "exploit"; $Hashes = Kind "sha256"; $Control = Kind "control"; $Dropped = Kind "dropped"; $Users = Kind "user" $Addr = New-Object System.Collections.Generic.HashSet[string] foreach ($l in ("$AddrText" -split "`r?`n")) { $v = $l.Trim(); if ($v -and -not $v.StartsWith("#")) { [void]$Addr.Add(($v -split "\s+")[0]) } } $Generated = ($Rows | Where-Object { $_[0] -eq "generated" } | Select-Object -First 1)[1] Out "Lists generated: $Generated Attacker addresses: $($Addr.Count) Ports: $($Ports.Count) Web paths: $($Paths.Count) Exploits: $($Exploits.Count)" Out "Malware hashes: $($Hashes.Count) Malware servers: $($Control.Count)" # ---- 1. listening services ----------------------------------------------------------------------------- Head "1. Services listening for connections" $Listen = @(Get-NetTCPConnection -State Listen) $Open = @{} foreach ($l in $Listen) { $local = ($l.LocalAddress -like "127.*") -or ($l.LocalAddress -eq "::1") if (-not $local) { $Open[[int]$l.LocalPort] = $true } } $FirewallOff = @(Get-NetFirewallProfile | Where-Object { -not $_.Enabled }) $WindowsDefault = @(135, 139, 445, 5985) # Windows listens here out of the box; the firewall decides who gets in if ($Listen.Count -eq 0) { Skip "Listening services could not be read on this version of Windows." } else { $found = $false foreach ($p in $Ports) { $port = [int]$p[1]; $name = $p[2]; $exposure = $p[3]; $seen = $p[4] if (-not $Open.ContainsKey($port)) { continue } $found = $true if ($WindowsDefault -contains $port -and $FirewallOff.Count -eq 0) { Look "Port $port ($name) is open on this machine, as on most Windows machines. $(SeenOn $seen)" More "The Windows firewall decides who reaches it. Never forward this port from your router to the internet." } elseif ($exposure -eq "never") { Warn "Port $port ($name) accepts connections from other machines. $(SeenOn $seen)" More "This service should never be reachable from the internet. Turn it off, or allow only your own addresses in the firewall." } else { Look "Port $port ($name) accepts connections from other machines. $(SeenOn $seen)" More "If it must be reachable, keep it updated and limit who can reach it." } } if (-not $found) { Ok "None of the $($Ports.Count) services attackers look for is listening for other machines." } Info "$($Open.Count) ports in total accept connections from other machines." More "Whether the internet reaches them depends on your firewall or router; this check sees only the machine itself." } if ($FirewallOff.Count -gt 0) { Warn ("The Windows firewall is off for: " + (($FirewallOff | ForEach-Object { $_.Name }) -join ", ") + ".") More "Turn it on in Windows Security, Firewall and network protection." } elseif (@(Get-NetFirewallProfile).Count -gt 0) { Ok "The Windows firewall is on for every network type." } # ---- 2. remote access and accounts --------------------------------------------------------------------- Head "2. Remote access and accounts" $ts = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server" $rdpSeen = ($Ports | Where-Object { $_[1] -eq "3389" } | Select-Object -First 1) $rdpSeen = if ($rdpSeen) { $rdpSeen[4] } else { 0 } if ($ts -and $ts.fDenyTSConnections -eq 0) { $nla = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp").UserAuthentication if ($nla -eq 0) { Warn "Remote Desktop is on and does not require sign-in before the session starts (Network Level Authentication is off). $(SeenOn $rdpSeen)" More "Turn on Network Level Authentication in System, Remote Desktop, and never forward port 3389 from the internet." } else { Info "Remote Desktop is on and requires sign-in before the session starts (Network Level Authentication). Reach it through a VPN; never forward port 3389 from the internet." } } else { Ok "Remote Desktop is off." } $guest = Get-LocalUser | Where-Object { $_.Enabled -and $_.SID.Value -like "*-501" } if ($guest) { Warn "The built-in Guest account is enabled. 'guest' is among the names attackers tried on our decoys."; More "Turn it off: Disable-LocalUser -Name '$($guest.Name)'" } $tried = @($Users | ForEach-Object { $_[1].ToLower() }) $named = @(Get-LocalUser | Where-Object { $_.Enabled -and ($tried -contains $_.Name.ToLower()) -and $_.SID.Value -notlike "*-501" }) if ($named.Count -gt 0) { Look ("Enabled accounts with names attackers try first: " + (($named | ForEach-Object { $_.Name }) -join ", ")) More "If any remote sign-in is open, these names are guessed all day. Give each a long, unique password, or rename or disable it." } elseif (Get-Command Get-LocalUser) { Ok "No enabled account carries one of the $($tried.Count) names attackers try first." } $sshd = Join-Path $env:ProgramData "ssh\sshd_config" if ($Open.ContainsKey(22) -and (Test-Path -LiteralPath $sshd)) { $pw = (Get-Content -LiteralPath $sshd | Where-Object { $_ -match "^\s*PasswordAuthentication\s+(\S+)" } | Select-Object -First 1) if (-not $pw -or $pw -match "yes") { Look "The Windows SSH server accepts passwords, and guessing them is the commonest attack on our SSH decoy."; More "Use keys and set 'PasswordAuthentication no' in $sshd." } else { Ok "The Windows SSH server does not accept passwords." } } # ---- 3. hashes ----------------------------------------------------------------------------------------- Head "3. Files in temporary folders, against captured malware" $winDropped = @($Dropped | Where-Object { $_[1] -match "^[A-Za-z]:\\" }) foreach ($d in $winDropped) { if (Test-Path -LiteralPath $d[1]) { Warn "$($d[1]) exists. $($d[2]) attacker addresses created a file with this exact name on our decoy."; More "Do not run it. Check when it appeared and what created it." } } if ($Hashes.Count -eq 0) { Info "The list has no malware hashes at the moment." } else { $bad = New-Object System.Collections.Generic.HashSet[string] foreach ($h in $Hashes) { [void]$bad.Add($h[1].ToLower()) } $dirs = @($env:TEMP, (Join-Path $env:windir "Temp"), $env:PUBLIC, (Join-Path $env:USERPROFILE "Downloads")) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -Unique $files = @(foreach ($d in $dirs) { Get-ChildItem -LiteralPath $d -File -Recurse -Depth 2 -Force | Where-Object { $_.Length -lt 20MB } | Select-Object -First 1000 }) $hits = 0; $done = 0 foreach ($f in $files) { $h = (Get-FileHash -LiteralPath $f.FullName -Algorithm SHA256).Hash if (-not $h) { continue } $done++ if ($bad.Contains($h.ToLower())) { $hits++; Warn "$($f.FullName) is a file our decoys captured from attackers (SHA-256 $($h.ToLower()))."; More "Do not run it. Disconnect the machine from the network and investigate how it arrived." } } if ($hits -eq 0) { Ok "$done files compared with $($bad.Count) captured malware files: no match." } More "Checked: your temporary folder, the Windows temporary folder, the Public folder and Downloads, three levels deep, files under 20 MB." More "The files our decoys have captured so far were built for Linux devices and Android, so a match on Windows would be unusual." } # ---- 4. malware servers -------------------------------------------------------------------------------- Head "4. Servers captured malware takes orders from" if ($Control.Count -eq 0) { Info "The list has no malware servers at the moment." } else { $needles = @($Control | ForEach-Object { $v = $_[2] if ($_[1] -eq "ip:port") { $v -replace ":\d+$", "" } elseif ($_[1] -eq "url") { ($v -replace "^[a-z]+://", "") -replace "[/:].*$", "" } else { $v } } | Sort-Object -Unique) $peers = @(Get-NetTCPConnection | Where-Object { $_.State -ne "Listen" } | ForEach-Object { $_.RemoteAddress } | Sort-Object -Unique) $peerHits = @($peers | Where-Object { $needles -contains $_ }) if ($peerHits.Count -gt 0) { foreach ($p in $peerHits) { Warn "This machine has an open connection with $p, a server our captured malware downloads from or takes orders from." } More "Find the program: Get-NetTCPConnection -RemoteAddress
| Select OwningProcess, then Get-Process -Id . Disconnect the machine from the network." } else { Ok "No open connection with any of the $($needles.Count) malware servers." } $names = @($needles | Where-Object { $_ -match "[A-Za-z]" }) # Windows shows every name in the hosts file as a recent lookup. Those are judged by their hosts line below, not here. $hosts = Join-Path $env:windir "System32\drivers\etc\hosts" $hostLines = @(if (Test-Path -LiteralPath $hosts) { Get-Content -LiteralPath $hosts | Where-Object { $_ -and -not $_.TrimStart().StartsWith("#") } }) $hostNames = @($hostLines | ForEach-Object { ($_.Trim() -split "\s+") | Select-Object -Skip 1 } | ForEach-Object { $_.ToLower() }) $dns = @(Get-DnsClientCache | ForEach-Object { $_.Entry } | Where-Object { $hostNames -notcontains "$_".ToLower() } | Sort-Object -Unique | Where-Object { $e = $_; @($names | Where-Object { $e -eq $_ -or $e.EndsWith(".$_") }).Count -gt 0 }) if ($dns.Count -gt 0) { foreach ($d in $dns) { Warn "This machine recently looked up $d, a name our captured malware uses to find its server." }; More "Some program on this machine asked for that name. Find out which before anything else." } elseif (Get-Command Get-DnsClientCache) { Ok "None of the malware server names is in the recent name lookups." } $start = New-Object System.Collections.Generic.List[string] foreach ($t in @(Get-ScheduledTask)) { foreach ($a in @($t.Actions)) { $start.Add(("Scheduled task '{0}{1}': {2} {3}" -f $t.TaskPath, $t.TaskName, $a.Execute, $a.Arguments)) } } foreach ($k in @("HKLM:\Software\Microsoft\Windows\CurrentVersion\Run", "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run", "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run", "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce", "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce")) { $item = if (Test-Path -Path $k) { Get-ItemProperty -Path $k } else { $null } if ($item) { foreach ($p in $item.PSObject.Properties) { if ($p.Name -notlike "PS*") { $start.Add("Start-up entry '$($p.Name)' in ${k}: $($p.Value)") } } } } # A hosts line that sends a malware name to 0.0.0.0 or 127.0.0.1 is a block, not a sign of trouble; any other address is. foreach ($l in $hostLines) { if ($l.Trim() -notmatch "^(0\.0\.0\.0|127\.|::1?\s)") { $start.Add("hosts file: $l") } } $startHits = @($start | Where-Object { $s = $_; @($needles | Where-Object { $s.IndexOf($_, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count -gt 0 }) if ($startHits.Count -gt 0) { foreach ($s in $startHits) { Warn "$s" }; More "These run by themselves and mention a malware server. If you did not create them, treat the machine as broken into." } else { Ok "No scheduled task, start-up entry or hosts line mentions a malware server ($($start.Count) entries read)." } } # ---- 5. web folders ------------------------------------------------------------------------------------ Head "5. Secret files inside web folders" $roots = @("C:\inetpub\wwwroot", "C:\xampp\htdocs", "C:\wamp64\www", "C:\wamp\www", "C:\nginx\html", "C:\laragon\www") | Where-Object { Test-Path -LiteralPath $_ } $webDirs = New-Object System.Collections.Generic.List[string] foreach ($r in $roots) { $webDirs.Add($r) foreach ($d in @(Get-ChildItem -LiteralPath $r -Directory -Force | Select-Object -First 40)) { $webDirs.Add($d.FullName) foreach ($sub in @("public", "public_html", "htdocs", "web")) { $p = Join-Path $d.FullName $sub; if (Test-Path -LiteralPath $p) { $webDirs.Add($p) } } } } if ($webDirs.Count -eq 0) { Ok "No web folder found in the usual places." More "If this machine serves a website from another folder, look there for .env, .git and backup files yourself." } else { $found = $false foreach ($d in $webDirs) { foreach ($p in $Paths) { $f = Join-Path $d ($p[1].TrimStart("/") -replace "/", "\") if (Test-Path -LiteralPath $f -PathType Leaf) { if ((Get-Item -LiteralPath $f -Force).Length -gt 0) { $found = $true; Warn "$f sits inside a web folder. $($p[2]) attacker addresses asked our websites for exactly this file." } } } } if ($found) { More "If the web server serves these files, anyone can read the secrets in them. Open the address in a browser to check," More "move the file out of the web folder, and change every password or key it holds." } else { Ok "$($webDirs.Count) web folders checked for $($Paths.Count) files attackers ask for: none present." } } # ---- 6. logs ------------------------------------------------------------------------------------------- Head "6. This machine's logs, against the addresses that attacked us" if ($Addr.Count -eq 0) { Skip "The address list could not be downloaded." } else { if (-not $IsAdmin) { Skip "The Windows sign-in log cannot be read without administrator rights." } else { $events = @(Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4624, 4625; StartTime = (Get-Date).AddDays(-14) } -MaxEvents 60000) $okHits = @{}; $failed = New-Object System.Collections.Generic.HashSet[string]; $failedAll = New-Object System.Collections.Generic.HashSet[string] foreach ($e in $events) { if ($e.Id -eq 4624) { $ip = [string]$e.Properties[18].Value; $type = [string]$e.Properties[8].Value; $user = [string]$e.Properties[5].Value if (($type -eq "3" -or $type -eq "10") -and $Addr.Contains($ip)) { $okHits["$ip as '$user'"] = $true } } else { $ip = [string]$e.Properties[19].Value if ($ip -and $ip -ne "-") { [void]$failedAll.Add($ip); if ($Addr.Contains($ip)) { [void]$failed.Add($ip) } } } } if ($okHits.Count -gt 0) { foreach ($k in $okHits.Keys) { Warn "A sign-in from the network SUCCEEDED from $k. That address attacked our decoys or servers." } More "Unless that address is yours (a shared or reassigned address can be), treat the account as taken over: change its password and review what it did." } else { Ok "No successful network sign-in from an address that attacked us ($($events.Count) sign-in records of the last 14 days read)." } Info "$($failed.Count) of the addresses that attacked us also tried to sign in to this machine and failed ($($failedAll.Count) failing sources in the log)." if ($failed.Count -gt 0) { More "That means a sign-in service on this machine is reachable from the internet. Find out which, and close it or put it behind a VPN." } } $iis = @(Get-ChildItem -Path "C:\inetpub\logs\LogFiles\*\*.log" | Sort-Object LastWriteTime -Descending | Select-Object -First 6) if ($iis.Count -eq 0) { Info "No IIS web server log found." } else { $pathSet = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase) foreach ($p in $Paths) { [void]$pathSet.Add($p[1]) } $rx = @(foreach ($x in $Exploits) { if ($x.Count -lt 6 -or $x[5] -ne "product") { try { [pscustomobject]@{ Cve = $x[1]; Product = $x[2]; Rx = New-Object Regex ($x[3]); Total = 0; Good = 0 } } catch { } } }) $visitors = New-Object System.Collections.Generic.HashSet[string]; $pathHits = @{}; $lines = 0 foreach ($log in $iis) { $iIp = -1; $iStem = -1; $iQuery = -1; $iStatus = -1 foreach ($line in @(Get-Content -LiteralPath $log.FullName -Tail 200000)) { if ($line.StartsWith("#Fields:")) { $f = $line.Substring(8).Trim() -split " " $iIp = [Array]::IndexOf($f, "c-ip"); $iStem = [Array]::IndexOf($f, "cs-uri-stem"); $iQuery = [Array]::IndexOf($f, "cs-uri-query"); $iStatus = [Array]::IndexOf($f, "sc-status") continue } if ($line.StartsWith("#") -or $iStem -lt 0) { continue } $c = $line -split " "; $lines++ if ($iIp -ge 0 -and $iIp -lt $c.Count) { [void]$visitors.Add($c[$iIp]) } $stem = $c[$iStem]; $status = if ($iStatus -ge 0 -and $iStatus -lt $c.Count) { $c[$iStatus] } else { "" } if ($pathSet.Contains($stem) -and $status.StartsWith("2")) { $pathHits[$stem] = 1 + [int]$pathHits[$stem] } $url = if ($iQuery -ge 0 -and $iQuery -lt $c.Count -and $c[$iQuery] -ne "-") { "$stem`?$($c[$iQuery])" } else { $stem } foreach ($r in $rx) { if ($r.Rx.IsMatch($url)) { $r.Total++; if ($status.StartsWith("2")) { $r.Good++ } } } } } $n = @($visitors | Where-Object { $Addr.Contains($_) }).Count Info "$n of the addresses that attacked us also visited this web server ($lines log lines, $($visitors.Count) visitor addresses)." if ($pathHits.Count -gt 0) { foreach ($k in $pathHits.Keys) { Warn "This web server answered $($pathHits[$k]) requests for $k with success. That is one of the files attackers ask websites for." } More "Open that address yourself. If it returns the real file, move it out of the web folder and change every secret in it." } else { Ok "No request for a file attackers look for was answered with success." } $seenAny = $false foreach ($r in $rx) { if ($r.Total -eq 0) { continue } $seenAny = $true if ($r.Good -gt 0) { Warn "$($r.Cve) ($($r.Product)): $($r.Total) attempts in the log, $($r.Good) answered with success."; More "If this machine runs $($r.Product), check its version against the fix for $($r.Cve) now." } else { Look "$($r.Cve) ($($r.Product)): $($r.Total) attempts in the log, none answered with success." } } if (-not $seenAny) { Ok "None of the exploit patterns we watch for appears in the web log." } } } # ---- summary ------------------------------------------------------------------------------------------- Head "Summary" Out " $($Count.warn) to act on (WARN), $($Count.look) worth a look (LOOK), $($Count.skip) checks skipped." if ($Count.skip -gt 0 -and -not $IsAdmin) { Out " Run it again in a PowerShell window opened as administrator to include the skipped checks." } Out " This compares your machine only with what ACIDRIPP has recorded so far. A clean result is not a clean bill of health." Out " Nothing about this machine was sent anywhere. What the checks mean: $Page" Out "" Out " Block the addresses behind these attacks before they reach you: our free firewall feed loads into" Out " most firewalls by itself and updates every few minutes. https://cybersecurity.acidripp.com/en/threat-feed/" if (-not $NoReport) { $file = Join-Path (Get-Location) ("acidripp-scan-report-{0}.txt" -f (Get-Date).ToUniversalTime().ToString("yyyyMMdd-HHmmss")) try { [IO.File]::WriteAllLines($file, $Report); Write-Host "`nReport saved: $file" } catch { Write-Host "`nThe report could not be saved in this folder." } }