Exploit database

GH-35104a8d013622b0366090d14f88f686

sxyrxyy/php2shell-cve-2026-109618-check

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

413 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files7
sxyrxyy/php2shell-cve-2026-109618-checkRevision df86e56848a5

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

php2shell-check.ps1

PowerShell · 43,236 bytes
<#
php2shell-check.ps1 - checks this Windows machine for the "php2shell" PHP bugs
(CVE-2026-109618, CVE-2026-109619).

It finds every PHP on the machine, tells you which copies have the fix, whether
PHP answers on a network port, and whether there are signs the machine is
already compromised. It never sends attack traffic and never contacts another
host except www.php.net (to learn the fixed versions).

Nothing on the machine is changed unless you answer y to a prompt. Every change
is logged with an undo.ps1 next to the backup.

Usage:
  powershell -ExecutionPolicy Bypass -File php2shell-check.ps1 [-CheckOnly] [-Json] [-Fixed "8.2.x 8.3.y"] [-NoColor]

Exit codes: 0 safe, 1 vulnerable, 2 vulnerable and reachable from the network,
3 signs of compromise (takes priority), 4 the check itself failed.

MIT License. Copyright (c) 2026 sxyrxyy.
#>

[CmdletBinding()]
param(
    [switch]$CheckOnly,
    [switch]$Json,
    [string]$Fixed,
    [switch]$NoColor
)

if ($Json) { $CheckOnly = $true }
$ProgressPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Continue'

# ---------------------------------------------------------------------------
# Data. New facts go here, not into the logic below.
# ---------------------------------------------------------------------------

$ToolVersion     = '1.0.0'
$CveIds          = @('CVE-2026-109618', 'CVE-2026-109619')
$FixCutoffDate   = [datetime]'2026-10-20'
$SupportedFrom   = [version]'8.2'
$KnownBranches   = @('8.2', '8.3', '8.4', '8.5')
$DownloadPage    = 'https://windows.php.net/download/'

# First fixed release per branch (php.net, 21 Oct 2026). Used when php.net can't be reached.
$EmbeddedFixed = @(
    '8.2 8.2.35'
    '8.3 8.3.36'
    '8.4 8.4.27'
    '8.5 8.5.12'
)

$PhpExeNames     = @('php.exe', 'php-cgi.exe')
$WebServerProcs  = @('w3wp', 'httpd', 'nginx', 'php', 'php-cgi', 'System')
$ShellChildren   = @('cmd.exe', 'powershell.exe', 'pwsh.exe', 'certutil.exe', 'bitsadmin.exe',
                     'wscript.exe', 'cscript.exe', 'curl.exe', 'mshta.exe')
$WorkerParents   = @('php-cgi.exe', 'php.exe', 'w3wp.exe', 'httpd.exe')
$WebshellMarkers = @('eval(base64_decode', 'eval(gzinflate', 'eval($_', 'system($_', 'shell_exec($_',
                     'passthru($_', 'exec($_', 'assert($_', 'popen($_', 'proc_open($_')
$NonHttpPorts    = @(135, 139, 445, 1433, 3306, 3389, 5432, 5985, 5986)
$RecentDays      = 7
$MaxProbePorts   = 20
$MaxPhpFiles     = 20000

# Fix table: id, condition, prompt text, apply function, undo text.
# Conditions and apply functions are defined further down.
$FixTable = @(
    @{ Id = 'stop-web'; Condition = 'Test-FixStopWeb'; Apply = 'Invoke-FixStopWeb' }
)

# ---------------------------------------------------------------------------
# State
# ---------------------------------------------------------------------------

$OnWindows = ($PSVersionTable.PSVersion.Major -lt 6) -or [bool](Get-Variable -Name IsWindows -ValueOnly -ErrorAction SilentlyContinue)
$IsPS7     = $PSVersionTable.PSVersion.Major -ge 7

$Result = [ordered]@{
    tool          = 'php2shell-check.ps1'
    toolVersion   = $ToolVersion
    cves          = $CveIds
    date          = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
    host          = [Environment]::MachineName
    isWindows     = $OnWindows
    isAdmin       = $false
    fixedSource   = ''
    fixedVersions = [ordered]@{}
    installs      = @()
    exposure      = [ordered]@{ checked = $false; listeners = @(); webServers = @(); phpSeenOnPorts = @() }
    compromise    = [ordered]@{ hits = @(); warnings = @() }
    skipped       = @()
    warnings      = @()
    verdict       = ''
    exitCode      = 4
}

$Installs      = New-Object System.Collections.ArrayList
$Listeners     = New-Object System.Collections.ArrayList
$WebServers    = New-Object System.Collections.ArrayList
$PhpPorts      = New-Object System.Collections.ArrayList
$CompHits      = New-Object System.Collections.ArrayList
$CompWarns     = New-Object System.Collections.ArrayList
$Skipped       = New-Object System.Collections.ArrayList
$Warnings      = New-Object System.Collections.ArrayList
$FixedMap      = @{}
$WebRoots      = New-Object System.Collections.ArrayList
$InventoryOk   = $false
$ExposureOk    = $false
$BackupDir     = $null

# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------

function Out-Line {
    param([string]$Text = '', [string]$Color = '')
    if ($Json) { return }
    if ($NoColor -or -not $Color) { Write-Host $Text } else { Write-Host $Text -ForegroundColor $Color }
}
function Out-Ok   { param([string]$t) Out-Line "[ OK ] $t" 'Green' }
function Out-Warn { param([string]$t) [void]$Warnings.Add($t); Out-Line "[WARN] $t" 'Yellow' }
function Out-Bad  { param([string]$t) Out-Line "[BAD ] $t" 'Red' }
function Out-Head { param([string]$t) Out-Line ''; Out-Line "== $t ==" 'Cyan' }
function Out-Skip {
    param([string]$t)
    [void]$Skipped.Add($t)
    Out-Line "skipped: $t"
}

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

function ConvertTo-PhpVersion {
    # "8.3.12-dev", "8.3.12.0", "8.3.12RC1" -> [version]8.3.12; $null when unreadable.
    param([string]$s)
    if (-not $s) { return $null }
    $m = [regex]::Match($s, '(\d+)\.(\d+)(?:\.(\d+))?')
    if (-not $m.Success) { return $null }
    $patch = 0
    if ($m.Groups[3].Success) { $patch = [int]$m.Groups[3].Value }
    return New-Object version ([int]$m.Groups[1].Value), ([int]$m.Groups[2].Value), $patch
}

function Get-Branch { param([version]$v) return '{0}.{1}' -f $v.Major, $v.Minor }

function ConvertFrom-PhpNetDate {
    param([string]$s)
    if (-not $s) { return $null }
    $formats = [string[]]@('dd MMM yyyy', 'd MMM yyyy')
    $out = [datetime]::MinValue
    if ([datetime]::TryParseExact($s.Trim(), $formats, [Globalization.CultureInfo]::InvariantCulture,
            [Globalization.DateTimeStyles]::None, [ref]$out)) { return $out }
    return $null
}

function Test-IsAdmin {
    if (-not $OnWindows) { return $false }
    try {
        $id = [Security.Principal.WindowsIdentity]::GetCurrent()
        return (New-Object Security.Principal.WindowsPrincipal $id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    } catch { return $false }
}

function Test-Interactive {
    if ($CheckOnly) { return $false }
    try {
        if (-not [Environment]::UserInteractive) { return $false }
        if ([Console]::IsInputRedirected) { return $false }
    } catch { return $false }
    return $true
}

function Read-YesNo {
    param([string]$Question)
    $a = Read-Host "$Question [y/N]"
    return ($a -match '^\s*(y|yes)\s*$')
}

function Get-PhpVersionFromBinary {
    # Reads the file version only. The binary is never run: a php.exe in a folder
    # other users can write to could be planted, and this script often runs elevated.
    # No version info means UNKNOWN, which counts as vulnerable.
    param([string]$Path)
    $info = [ordered]@{ version = $null; raw = ''; source = '' }
    try {
        $vi = (Get-Item -LiteralPath $Path -ErrorAction Stop).VersionInfo
        $v = ConvertTo-PhpVersion $vi.ProductVersion
        if (-not $v) { $v = ConvertTo-PhpVersion $vi.FileVersion }
        if ($v) { $info.version = $v; $info.raw = [string]$vi.ProductVersion; $info.source = 'file version' }
    } catch { }
    return $info
}

function Get-IisConfigPath {
    if (-not $OnWindows -or -not $env:windir) { return $null }
    $dir = Join-Path $env:windir 'System32\inetsrv\config'
    if (-not [Environment]::Is64BitProcess -and [Environment]::Is64BitOperatingSystem) {
        $dir = Join-Path $env:windir 'Sysnative\inetsrv\config'
    }
    return (Join-Path $dir 'applicationHost.config')
}

# ---------------------------------------------------------------------------
# Phase 1.1: fixed versions
# ---------------------------------------------------------------------------

function Get-FixedFromPhpNet {
    param([string[]]$Branches)
    $map = @{}
    $reached = $false
    if (-not $IsPS7) {
        try {
            [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
        } catch { }
    }
    foreach ($b in $Branches) {
        try {
            $url = "https://www.php.net/releases/index.php?json&max=20&version=$b"
            $r = Invoke-RestMethod -Uri $url -TimeoutSec 10 -UseBasicParsing -ErrorAction Stop
            $reached = $true
            if ($r.PSObject.Properties.Name -contains 'error') { continue }
            $best = $null
            foreach ($prop in $r.PSObject.Properties) {
                $v = ConvertTo-PhpVersion $prop.Name
                $d = ConvertFrom-PhpNetDate ([string]$prop.Value.date)
                if (-not $v -or -not $d) { continue }
                if ((Get-Branch $v) -ne $b) { continue }
                if ($d -lt $FixCutoffDate) { continue }
                if (-not $best -or $v -lt $best) { $best = $v }
            }
            if ($best) { $map[$b] = $best }
        } catch { }
    }
    return @{ reached = $reached; map = $map }
}

function Resolve-FixedVersions {
    param([string[]]$Branches)
    Out-Head 'Fixed versions'
    if ($Fixed) {
        foreach ($tok in ($Fixed -split '[\s,;]+')) {
            $v = ConvertTo-PhpVersion $tok
            if ($v) { $FixedMap[(Get-Branch $v)] = $v }
        }
        $Result.fixedSource = 'override (-Fixed)'
    } else {
        $net = Get-FixedFromPhpNet -Branches $Branches
        if ($net.map.Count -gt 0) {
            foreach ($k in $net.map.Keys) { $FixedMap[$k] = $net.map[$k] }
            $Result.fixedSource = 'php.net'
        } else {
            foreach ($line in $EmbeddedFixed) {
                $parts = ($line -split '\s+') | Where-Object { $_ }
                if ($parts.Count -ge 2) {
                    $v = ConvertTo-PhpVersion $parts[1]
                    if ($v) { $FixedMap[$parts[0]] = $v }
                }
            }
            if ($net.reached) {
                $Result.fixedSource = 'php.net (no release dated on or after 2026-10-20); embedded list'
            } else {
                $Result.fixedSource = 'embedded list (php.net not reachable)'
            }
        }
    }
    Out-Line "source: $($Result.fixedSource)"
    foreach ($b in $Branches) {
        if ($FixedMap.ContainsKey($b)) {
            Out-Line ("  {0}: fixed in {1}" -f $b, $FixedMap[$b])
            $Result.fixedVersions[$b] = [string]$FixedMap[$b]
        } else {
            Out-Line ("  {0}: no fixed version known (check php.net, rerun with -Fixed)" -f $b)
            $Result.fixedVersions[$b] = $null
        }
    }
}

# ---------------------------------------------------------------------------
# Phase 1.2: inventory
# ---------------------------------------------------------------------------

function Find-PhpBinaries {
    $seen = New-Object 'System.Collections.Generic.Dictionary[string,string]' ([StringComparer]::OrdinalIgnoreCase)
    $add = {
        param($path, $where)
        if (-not $path) { return }
        try { $full = (Resolve-Path -LiteralPath $path -ErrorAction Stop).ProviderPath } catch { return }
        if (-not $seen.ContainsKey($full)) { $seen[$full] = $where }
    }

    # PATH
    foreach ($n in $PhpExeNames) {
        foreach ($c in @(Get-Command $n -CommandType Application -All -ErrorAction SilentlyContinue)) {
            & $add $c.Source 'PATH'
        }
    }

    if (-not $OnWindows) { return $seen }

    $sysDrive = $env:SystemDrive
    if (-not $sysDrive) { $sysDrive = 'C:' }
    $root = "$sysDrive\"

    # Fixed locations: C:\php*, C:\xampp\php, C:\wamp*\bin\php\*, C:\laragon\bin\php\*
    $dirs = New-Object System.Collections.ArrayList
    foreach ($d in @(Get-ChildItem -LiteralPath $root -Directory -Filter 'php*' -ErrorAction SilentlyContinue)) { [void]$dirs.Add($d.FullName) }
    [void]$dirs.Add((Join-Path $root 'xampp\php'))
    foreach ($w in @(Get-ChildItem -LiteralPath $root -Directory -Filter 'wamp*' -ErrorAction SilentlyContinue)) {
        foreach ($d in @(Get-ChildItem -LiteralPath (Join-Path $w.FullName 'bin\php') -Directory -ErrorAction SilentlyContinue)) { [void]$dirs.Add($d.FullName) }
    }
    foreach ($d in @(Get-ChildItem -LiteralPath (Join-Path $root 'laragon\bin\php') -Directory -ErrorAction SilentlyContinue)) { [void]$dirs.Add($d.FullName) }
    foreach ($d in $dirs) {
        foreach ($n in $PhpExeNames) {
            $p = Join-Path $d $n
            if (Test-Path -LiteralPath $p) { & $add $p 'install dir' }
        }
    }

    # Program Files, depth-limited
    foreach ($pf in @($env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:ProgramW6432) | Select-Object -Unique) {
        if (-not $pf -or -not (Test-Path -LiteralPath $pf)) { continue }
        foreach ($f in @(Get-ChildItem -LiteralPath $pf -Recurse -Depth 4 -File -Filter 'php*.exe' -ErrorAction SilentlyContinue)) {
            if ($PhpExeNames -contains $f.Name.ToLowerInvariant()) { & $add $f.FullName 'Program Files' }
        }
    }

    # IIS FastCGI (read-only)
    $cfg = Get-IisConfigPath
    if ($cfg -and (Test-Path -LiteralPath $cfg)) {
        try {
            [xml]$x = Get-Content -LiteralPath $cfg -Raw -ErrorAction Stop
            foreach ($app in @($x.SelectNodes('/configuration/system.webServer/fastCgi/application'))) {
                $fp = [Environment]::ExpandEnvironmentVariables([string]$app.fullPath)
                if ($fp -match 'php') { & $add $fp 'IIS FastCGI' }
            }
            foreach ($vd in @($x.SelectNodes('/configuration/system.applicationHost/sites/site/application/virtualDirectory'))) {
                $pp = [Environment]::ExpandEnvironmentVariables([string]$vd.physicalPath)
                if ($pp) { [void]$WebRoots.Add($pp) }
            }
        } catch {
            Out-Skip 'IIS config not readable (run as Administrator to include it)'
        }
    }

    # Running PHP processes
    try {
        foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='php.exe' OR Name='php-cgi.exe'" -ErrorAction Stop)) {
            if ($p.ExecutablePath) { & $add $p.ExecutablePath 'running process' }
        }
    } catch {
        foreach ($p in @(Get-Process -Name php, php-cgi -ErrorAction SilentlyContinue)) {
            if ($p.Path) { & $add $p.Path 'running process' }
        }
    }
    return $seen
}

function Invoke-Inventory {
    $bins = Find-PhpBinaries
    foreach ($path in $bins.Keys) {
        $vinfo = Get-PhpVersionFromBinary -Path $path
        $sapi = 'cli'
        if ((Split-Path -Leaf $path) -ieq 'php-cgi.exe') { $sapi = 'cgi-fcgi' }
        $inst = [ordered]@{
            path          = $path
            foundBy       = $bins[$path]
            version       = $(if ($vinfo.version) { [string]$vinfo.version } else { $null })
            versionSource = $vinfo.source
            sapi          = $sapi
            branch        = $(if ($vinfo.version) { Get-Branch $vinfo.version } else { $null })
            status        = 'UNKNOWN'
            detail        = ''
            fixedIn       = $null
        }
        [void]$Installs.Add($inst)
    }
    $script:InventoryOk = $true
}

function Set-InstallStatus {
    foreach ($i in $Installs) {
        if (-not $i.version) {
            $i.status = 'UNKNOWN'; $i.detail = 'version could not be read'
            continue
        }
        $v = [version]$i.version
        $b = $i.branch
        if ($FixedMap.ContainsKey($b)) { $i.fixedIn = [string]$FixedMap[$b] }
        if ($FixedMap.ContainsKey($b) -and $v -ge $FixedMap[$b]) {
            $i.status = 'PATCHED'; $i.detail = "fixed in $($FixedMap[$b])"
        } elseif ((New-Object version $v.Major, $v.Minor) -lt $SupportedFrom) {
            $i.status = 'VULNERABLE'; $i.detail = 'end-of-life, no fix coming'
        } elseif ($FixedMap.ContainsKey($b)) {
            $i.status = 'VULNERABLE'; $i.detail = "fix available: $($FixedMap[$b])"
        } else {
            $i.status = 'VULNERABLE'; $i.detail = 'no fix yet'
        }
    }
    if ($Installs.Count -eq 0) { Out-Line 'no php.exe or php-cgi.exe found'; return }
    foreach ($i in $Installs) {
        $label = "PHP $(if ($i.version) { $i.version } else { '?' }) ($($i.sapi)) $($i.path) [$($i.foundBy)]: $($i.status), $($i.detail)"
        switch ($i.status) {
            'PATCHED' { Out-Ok $label }
            default   { Out-Bad $label }
        }
    }
}

# ---------------------------------------------------------------------------
# Phase 1.4: exposure
# ---------------------------------------------------------------------------

function Invoke-HeaderProbe {
    # One plain GET, headers only, 4 s timeout. Returns status, X-Powered-By, Set-Cookie.
    param([string]$Url)
    $r = @{ status = 0; powered = ''; cookie = '' }
    if ($IsPS7) {
        # With -MaximumRedirection 0, PowerShell 7 returns the 3xx response and
        # also raises an error; -ErrorAction Stop would lose the response.
        try {
            $resp = Invoke-WebRequest -Uri $Url -Method Get -TimeoutSec 4 -MaximumRedirection 0 -UseBasicParsing `
                        -SkipCertificateCheck -SkipHttpErrorCheck -ErrorAction SilentlyContinue
            if (-not $resp) { return $r }
            $r.status  = [int]$resp.StatusCode
            $r.powered = (@($resp.Headers['X-Powered-By']) -join ' ')
            $r.cookie  = (@($resp.Headers['Set-Cookie']) -join ' ')
        } catch { }
        return $r
    }
    # Windows PowerShell 5.1: HttpWebRequest does not follow redirects here and
    # lets us read headers without the body. The certificate callback is
    # process-wide, so it is restored right after.
    $prevCb = [Net.ServicePointManager]::ServerCertificateValidationCallback
    $resp = $null
    try {
        [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
        $req = [Net.HttpWebRequest]::Create($Url)
        $req.Method = 'GET'
        $req.Timeout = 4000
        $req.ReadWriteTimeout = 4000
        $req.AllowAutoRedirect = $false
        $req.UserAgent = "php2shell-check/$ToolVersion"
        try {
            $resp = $req.GetResponse()
        } catch [Net.WebException] {
            $resp = $_.Exception.Response
        }
        if ($resp) {
            $r.status  = [int]$resp.StatusCode
            $r.powered = [string]$resp.Headers['X-Powered-By']
            $r.cookie  = [string]$resp.Headers['Set-Cookie']
        }
    } catch {
    } finally {
        if ($resp) { try { $resp.Close() } catch { } }
        [Net.ServicePointManager]::ServerCertificateValidationCallback = $prevCb
    }
    return $r
}

function Test-PhpOnPort {
    param([string]$Address, [int]$Port)
    $target = '127.0.0.1'
    if ($Address -and $Address -notin @('0.0.0.0', '::', '[::]')) {
        $target = $Address
        if ($Address -match ':') { $target = "[$Address]" }
    }
    $schemes = @('http')
    if ($Port -in @(443, 8443)) { $schemes = @('https', 'http') }
    foreach ($s in $schemes) {
        $base = "{0}://{1}:{2}" -f $s, $target, $Port
        $root = Invoke-HeaderProbe "$base/"
        # No HTTP answer on "/": not a web server on this scheme, skip the other two requests.
        if ($root.status -eq 0) { continue }
        $idx  = Invoke-HeaderProbe "$base/index.php"
        $rnd  = Invoke-HeaderProbe ("$base/" + [guid]::NewGuid().ToString('N') + '.php')
        $why = @()
        foreach ($p in @($root, $idx, $rnd)) {
            if ($p.powered -match 'PHP') { $why += "X-Powered-By: $($p.powered)" ; break }
        }
        foreach ($p in @($root, $idx, $rnd)) {
            if ($p.cookie -match 'PHPSESSID') { $why += 'PHPSESSID cookie'; break }
        }
        if ($idx.status -eq 200 -and $rnd.status -ne 200) { $why += '/index.php returns 200' }
        return @{ answered = $true; seen = ($why.Count -gt 0); why = ($why -join ', '); scheme = $s }
    }
    return @{ answered = $false; seen = $false; why = ''; scheme = '' }
}

function Invoke-Exposure {
    Out-Head 'Network exposure'
    if (-not $OnWindows) { Out-Skip 'exposure check: not running on Windows'; return }

    # Web servers
    $svcPattern = '^(W3SVC|WAS|Apache.*|httpd.*|nginx.*)$'
    try {
        foreach ($s in @(Get-Service -ErrorAction Stop | Where-Object {
                $_.Status -eq 'Running' -and ($_.Name -match $svcPattern -or $_.DisplayName -match 'Apache|nginx|World Wide Web Publishing') })) {
            [void]$WebServers.Add([ordered]@{ kind = 'service'; name = $s.Name; displayName = $s.DisplayName })
        }
    } catch { Out-Skip 'service list not readable' }
    foreach ($p in @(Get-Process -Name w3wp, httpd, nginx -ErrorAction SilentlyContinue | Select-Object -Property Name -Unique)) {
        [void]$WebServers.Add([ordered]@{ kind = 'process'; name = "$($p.Name).exe"; displayName = '' })
    }
    if ($WebServers.Count -gt 0) {
        Out-Line ('web servers running: ' + (($WebServers | ForEach-Object { $_.name }) -join ', '))
    } else {
        Out-Line 'no IIS, Apache or nginx running'
    }

    if (-not (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue)) {
        Out-Skip 'listening ports: Get-NetTCPConnection not available on this Windows version'
        return
    }
    try {
        $conns = @(Get-NetTCPConnection -State Listen -ErrorAction Stop)
    } catch {
        Out-Skip "listening ports: $($_.Exception.Message)"
        return
    }
    $procNames = @{}
    foreach ($p in @(Get-Process -ErrorAction SilentlyContinue)) { $procNames[[int]$p.Id] = $p.Name }

    $public = $conns | Where-Object {
        $_.LocalAddress -ne '::1' -and $_.LocalAddress -notlike '127.*' -and $_.LocalAddress -ne '::ffff:127.0.0.1'
    }
    $byPort = @{}
    foreach ($c in $public) {
        $port = [int]$c.LocalPort
        if ($byPort.ContainsKey($port)) { continue }
        $pname = $procNames[[int]$c.OwningProcess]
        if (-not $pname) { $pname = "pid $($c.OwningProcess)" }
        $byPort[$port] = [ordered]@{ port = $port; address = [string]$c.LocalAddress; process = $pname; pid = [int]$c.OwningProcess; probed = $false; phpSeen = $false; why = '' }
    }
    $script:ExposureOk = $true
    $Result.exposure.checked = $true

    $probed = 0
    foreach ($port in ($byPort.Keys | Sort-Object)) {
        $l = $byPort[$port]
        [void]$Listeners.Add($l)
        if ($NonHttpPorts -contains $port) { continue }
        if ($probed -ge $MaxProbePorts) { continue }
        $probed++
        $t = Test-PhpOnPort -Address $l.address -Port $port
        $l.probed = $true
        $isPhpProc = $l.process -match '^php(-cgi)?$'
        if ($t.seen -or $isPhpProc) {
            $l.phpSeen = $true
            $l.why = $(if ($t.seen) { $t.why } else { 'port owned by a PHP process' })
            [void]$PhpPorts.Add($port)
        }
    }
    if ($probed -ge $MaxProbePorts) { Out-Line "probed the first $MaxProbePorts ports only" }

    if ($Listeners.Count -eq 0) { Out-Line 'no TCP ports listening outside loopback' }
    foreach ($l in $Listeners) {
        $line = "port $($l.port) on $($l.address) ($($l.process))"
        if ($l.phpSeen) {
            Out-Bad "$line answers with PHP: $($l.why)"
        } elseif ($l.probed -and $WebServerProcs -contains $l.process) {
            Out-Line "$line : web server, PHP not seen in headers"
        } else {
            Out-Line $line
        }
    }
    if ($PhpPorts.Count -eq 0 -and ($Listeners | Where-Object { $WebServerProcs -contains $_.process })) {
        Out-Line 'a web server listens on the network but did not show PHP; a PHP site can still sit behind other paths or host names'
    }

    # Firewall: print only, do not reason about it.
    if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) {
        try {
            $fw = @(Get-NetFirewallProfile -ErrorAction Stop | ForEach-Object { "$($_.Name)=$(if ($_.Enabled) { 'on' } else { 'off' })" })
            Out-Line ('Windows Firewall profiles: ' + ($fw -join ', '))
        } catch { }
    }
}

# ---------------------------------------------------------------------------
# Phase 1.5: signs of compromise (report only)
# ---------------------------------------------------------------------------

function Add-CompHit  { param([string]$t) [void]$CompHits.Add($t);  Out-Bad $t }
function Add-CompWarn { param([string]$t) [void]$CompWarns.Add($t); Out-Warn $t }

function Test-ChildProcesses {
    try {
        $all = @(Get-CimInstance Win32_Process -ErrorAction Stop)
    } catch {
        Out-Skip "process tree: $($_.Exception.Message)"
        return
    }
    $byPid = @{}
    foreach ($p in $all) { $byPid[[int]$p.ProcessId] = $p }
    $found = 0
    foreach ($p in $all) {
        if ($ShellChildren -notcontains ([string]$p.Name).ToLowerInvariant()) { continue }
        $parent = $byPid[[int]$p.ParentProcessId]
        if (-not $parent) { continue }
        if ($WorkerParents -notcontains ([string]$parent.Name).ToLowerInvariant()) { continue }
        # A parent created after the child is a reused PID, not the real parent.
        if ($parent.CreationDate -and $p.CreationDate -and $parent.CreationDate -gt $p.CreationDate) { continue }
        $cmd = [string]$p.CommandLine
        if ($cmd.Length -gt 200) { $cmd = $cmd.Substring(0, 200) + '...' }
        Add-CompHit ("{0} (pid {1}) started by {2} (pid {3}): {4}" -f $p.Name, $p.ProcessId, $parent.Name, $parent.ProcessId, $cmd)
        $found++
    }
    if ($found -eq 0) { Out-Ok 'no shell or download tool running under PHP or a web server worker' }
}

function Get-WebRootList {
    $sysDrive = $env:SystemDrive
    if (-not $sysDrive) { $sysDrive = 'C:' }
    $cands = New-Object System.Collections.ArrayList
    foreach ($r in $WebRoots) { [void]$cands.Add($r) }
    [void]$cands.Add("$sysDrive\inetpub\wwwroot")
    [void]$cands.Add("$sysDrive\xampp\htdocs")
    [void]$cands.Add("$sysDrive\laragon\www")
    foreach ($w in @(Get-ChildItem -LiteralPath "$sysDrive\" -Directory -Filter 'wamp*' -ErrorAction SilentlyContinue)) {
        [void]$cands.Add((Join-Path $w.FullName 'www'))
    }
    $out = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
    foreach ($c in $cands) {
        if ($c -and (Test-Path -LiteralPath $c -PathType Container)) { [void]$out.Add($c) }
    }
    return @($out)
}

function Test-WebRootFiles {
    $roots = Get-WebRootList
    if ($roots.Count -eq 0) { Out-Line 'no web roots found to scan'; return }
    $since = (Get-Date).AddDays(-$RecentDays)
    $recent = New-Object System.Collections.ArrayList
    $count = 0
    $capped = $false
    foreach ($r in $roots) {
        foreach ($f in (Get-ChildItem -LiteralPath $r -Recurse -Depth 12 -File -Filter '*.php' -ErrorAction SilentlyContinue)) {
            $count++
            if ($count -gt $MaxPhpFiles) { $capped = $true; break }
            if ($f.LastWriteTime -ge $since -or $f.CreationTime -ge $since) { [void]$recent.Add($f) }
        }
        if ($capped) { break }
    }
    Out-Line ("scanned {0} .php files in: {1}" -f [Math]::Min($count, $MaxPhpFiles), ($roots -join ', '))
    if ($capped) { Out-Warn "stopped after $MaxPhpFiles .php files; the rest of the web roots were not scanned" }

    $marked = 0
    foreach ($f in $recent) {
        $hit = $null
        try { $hit = Select-String -LiteralPath $f.FullName -SimpleMatch -Pattern $WebshellMarkers -List -ErrorAction Stop } catch { }
        if ($hit) {
            Add-CompHit ("webshell marker '{0}' in {1} (modified {2:yyyy-MM-dd HH:mm})" -f $hit.Pattern, $f.FullName, $f.LastWriteTime)
            $marked++
        }
    }
    if ($recent.Count -gt 0) {
        $list = ($recent | Sort-Object LastWriteTime -Descending | Select-Object -First 10 | ForEach-Object { $_.FullName }) -join '; '
        $more = ''
        if ($recent.Count -gt 10) { $more = " (and $($recent.Count - 10) more)" }
        Add-CompWarn ("{0} .php files changed in the last {1} days; check you made these changes: {2}{3}" -f $recent.Count, $RecentDays, $list, $more)
    } else {
        Out-Ok "no .php files changed in the last $RecentDays days"
    }
    if ($recent.Count -gt 0 -and $marked -eq 0) { Out-Line 'none of the changed files contain common webshell markers' }
}

function Test-ScheduledTasks {
    if (-not (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) {
        Out-Skip 'scheduled tasks: Get-ScheduledTask not available'
        return
    }
    try { $tasks = @(Get-ScheduledTask -ErrorAction Stop) } catch { Out-Skip "scheduled tasks: $($_.Exception.Message)"; return }
    $since = (Get-Date).AddDays(-$RecentDays)
    $tasksDir = Join-Path $env:windir 'System32\Tasks'
    # BAD: a shell or download tool, or an encoded/downloading command line.
    # WARN: other new tasks, flagged louder when they run from temp or a web root.
    $badExe  = '(?i)(^|\\)(cmd|powershell|pwsh|certutil|bitsadmin|wscript|cscript|mshta|curl)(\.exe)?$'
    $badArg  = '(?i)(-enc\b|-encodedcommand|frombase64string|downloadstring|downloadfile)'
    $oddPath = '(?i)(\\temp\\|\\appdata\\|\\users\\public\\|inetpub|htdocs|\\www\\)'
    $new = 0
    foreach ($t in $tasks) {
        if ($t.TaskPath -like '\Microsoft\*') { continue }
        $created = $null
        if ($t.Date) { try { $created = [datetime]$t.Date } catch { } }
        if (-not $created) {
            $f = Join-Path $tasksDir (($t.TaskPath.TrimStart('\')) + $t.TaskName)
            try { $created = (Get-Item -LiteralPath $f -ErrorAction Stop).LastWriteTime } catch { }
        }
        if (-not $created -or $created -lt $since) { continue }
        $new++
        $actions = @($t.Actions | ForEach-Object { ("{0} {1}" -f $_.Execute, $_.Arguments).Trim() })
        $text = $actions -join ' | '
        $suspicious = $false
        $odd = $false
        foreach ($a in @($t.Actions)) {
            $exe = [Environment]::ExpandEnvironmentVariables([string]$a.Execute).Trim('"')
            if ($exe -match $badExe -or [string]$a.Arguments -match $badArg) { $suspicious = $true }
            if ("$exe $($a.Arguments)" -match $oddPath) { $odd = $true }
        }
        $line = "scheduled task $($t.TaskPath)$($t.TaskName) created $($created.ToString('yyyy-MM-dd')): $text"
        if ($suspicious) {
            Add-CompHit $line
        } elseif ($odd) {
            Add-CompWarn "$line (new task running from a temp, profile or web folder; check you know it)"
        } else {
            Add-CompWarn "$line (new task; check you know it)"
        }
    }
    if ($new -eq 0) { Out-Ok "no non-Microsoft scheduled tasks created in the last $RecentDays days" }
}

function Invoke-Compromise {
    Out-Head 'Signs of compromise (report only)'
    if (-not $OnWindows) { Out-Skip 'compromise checks: not running on Windows'; return }
    try { Test-ChildProcesses } catch { Out-Skip "process tree: $($_.Exception.Message)" }
    try { Test-WebRootFiles } catch { Out-Skip "web root scan: $($_.Exception.Message)" }
    try { Test-ScheduledTasks } catch { Out-Skip "scheduled tasks: $($_.Exception.Message)" }
}

# ---------------------------------------------------------------------------
# Phase 1.6: verdict
# ---------------------------------------------------------------------------

function Get-Verdict {
    $bad = @($Installs | Where-Object { $_.status -ne 'PATCHED' })
    $verdict = ''; $code = 4; $color = 'Red'; $todo = @()

    if ($CompHits.Count -gt 0) {
        $verdict = "SIGNS OF COMPROMISE: $($CompHits.Count) finding(s) above"
        $code = 3
        $todo = @(
            'Isolate this machine from the network now (unplug it or block it at the firewall).',
            'Keep the evidence: do not delete files, kill processes or reboot. Copy the web server logs (C:\inetpub\logs, Apache/nginx logs) and the Windows event logs somewhere safe.',
            'Get incident response help before you patch or clean anything. This script will not offer fixes.'
        )
    } elseif (-not $OnWindows) {
        $verdict = 'CHECK INCOMPLETE: this script is for Windows; use php2shell-check.sh on Linux'
        $code = 4
    } elseif (-not $InventoryOk) {
        $verdict = 'CHECK INCOMPLETE: could not search this machine for PHP'
        $code = 4
    } elseif ($Installs.Count -eq 0) {
        $verdict = 'NO PHP: nothing on this server runs PHP'
        $code = 0; $color = 'Green'
    } elseif ($bad.Count -eq 0) {
        $verdict = 'PATCHED: all PHP on this server has the fix'
        $code = 0; $color = 'Green'
    } else {
        $vers = (@($bad | ForEach-Object { if ($_.version) { $_.version } else { 'unknown version' } }) | Select-Object -Unique) -join ', '
        if ($PhpPorts.Count -gt 0) {
            $ports = (@($PhpPorts) | Sort-Object -Unique) -join ', '
            $verdict = "VULNERABLE AND PUBLIC: PHP $vers on port $ports"
            $code = 2
        } else {
            $verdict = "VULNERABLE: PHP $vers (not seen on a network port)"
            if (-not $ExposureOk) { $verdict = "VULNERABLE: PHP $vers (could not check network exposure)" }
            $code = 1; $color = 'Yellow'
        }
        $noFix = @($bad | Where-Object { $_.detail -eq 'no fix yet' })
        $unk   = @($bad | Where-Object { $_.status -eq 'UNKNOWN' })
        $eol   = @($bad | Where-Object { $_.detail -like 'end-of-life*' })
        $avail = @($bad | Where-Object { $_.detail -like 'fix available*' })
        if ($avail.Count -gt 0) {
            $todo += "Replace the PHP builds marked 'fix available' with the fixed build from $DownloadPage (folders listed below)."
        }
        if ($noFix.Count -gt 0) {
            $todo += "No fixed version is known for these PHP branches. Check $DownloadPage and rerun with -Fixed. Until then: stop or firewall the public PHP site."
        }
        if ($eol.Count -gt 0) {
            $todo += 'PHP below 8.2 gets no fix. Move these sites to PHP 8.2 or newer, or take them off the network: ' + (($eol | ForEach-Object { "$($_.path) ($($_.version))" }) -join '; ')
        }
        if ($unk.Count -gt 0) {
            $todo += 'Could not read the version of: ' + (($unk | ForEach-Object { $_.path }) -join '; ') + '. Run "<path> -v" by hand; treat it as vulnerable until you know.'
        }
        if (-not $ExposureOk) { Out-Warn 'could not tell whether PHP is reachable from the network; treat it as public' }
    }
    return @{ verdict = $verdict; code = $code; color = $color; todo = $todo }
}

function Get-HostMessage {
    $bad = @($Installs | Where-Object { $_.status -ne 'PATCHED' })
    $lines = @(
        'Subject: Please patch PHP for CVE-2026-109618 / CVE-2026-109619 (php2shell)',
        '',
        'Hello,',
        '',
        "My server $([Environment]::MachineName) runs PHP builds that do not have the fix for CVE-2026-109618 and CVE-2026-109619 (php2shell, announced by the PHP security team on 20 Oct 2026):"
    )
    foreach ($i in $bad) { $lines += "  - PHP $(if ($i.version) { $i.version } else { '(version unknown)' }), SAPI $($i.sapi), $($i.path)" }
    $lines += ''
    $lines += 'Please update PHP to a fixed release (PHP 8.2 or newer), or tell me when you will. If no fixed build is available yet, please tell me how you are protecting the site until then.'
    $lines += ''
    $lines += 'Thank you.'
    return $lines
}

# ---------------------------------------------------------------------------
# Phase 2: fixes (interactive)
# ---------------------------------------------------------------------------

function New-BackupDir {
    if ($script:BackupDir) { return $script:BackupDir }
    # Lives in the profile of the user running the script (only they and SYSTEM can
    # write there), with a random suffix, and must not exist yet. A shared folder like
    # ProgramData would let another user swap undo.ps1 before an admin runs it.
    $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
    $suffix = [guid]::NewGuid().ToString('N').Substring(0, 8)
    $dir = Join-Path $HOME "php2shell-backup-$stamp-$suffix"
    New-Item -ItemType Directory -Path $dir -ErrorAction Stop | Out-Null
    $undo = @(
        '# undo.ps1 - reverses the changes php2shell-check.ps1 made.',
        '# Run in an elevated PowerShell: powershell -ExecutionPolicy Bypass -File undo.ps1',
        '$ErrorActionPreference = ''Continue'''
    )
    Set-Content -LiteralPath (Join-Path $dir 'undo.ps1') -Value $undo -Encoding ASCII
    Set-Content -LiteralPath (Join-Path $dir 'changes.log') -Value "php2shell-check.ps1 $ToolVersion on $([Environment]::MachineName), started $((Get-Date).ToString('u'))" -Encoding ASCII
    $script:BackupDir = $dir
    return $dir
}

function Add-UndoLine {
    param([string]$Line, [string]$Log)
    $dir = New-BackupDir
    Add-Content -LiteralPath (Join-Path $dir 'undo.ps1') -Value $Line -Encoding ASCII
    Add-Content -LiteralPath (Join-Path $dir 'changes.log') -Value "$((Get-Date).ToString('u')) $Log" -Encoding ASCII
}

function Get-StoppableWebServices {
    try {
        return @(Get-Service -ErrorAction Stop | Where-Object {
            $_.Status -eq 'Running' -and ($_.Name -match '^(W3SVC|Apache.*|httpd.*|nginx.*)$' -or $_.DisplayName -match 'Apache|nginx|World Wide Web Publishing')
        })
    } catch { return @() }
}

function Test-FixStopWeb {
    if ($PhpPorts.Count -eq 0) { return $false }
    $needs = @($Installs | Where-Object { $_.status -ne 'PATCHED' -and ($_.detail -eq 'no fix yet' -or $_.detail -like 'end-of-life*' -or $_.status -eq 'UNKNOWN') })
    if ($needs.Count -eq 0) { return $false }
    return ((Get-StoppableWebServices).Count -gt 0)
}

function Invoke-FixStopWeb {
    $svcs = Get-StoppableWebServices
    $names = ($svcs | ForEach-Object { $_.Name }) -join ', '
    Out-Line ''
    Out-Line 'Fix: temporary shutdown of the public web server'
    Out-Line "  What it changes: stops these services: $names"
    Out-Line '  Why: PHP here answers on a network port and has no fix (or is end-of-life). Stopping the web server closes the hole until you can patch.'
    Out-Line ('  Command: ' + (($svcs | ForEach-Object { "Stop-Service -Name '$($_.Name)' -Force" }) -join '; '))
    Out-Line '  Downtime: YES. Every site served by these services goes offline until you start them again.'
    Out-Line '  The services are stopped, not disabled: a reboot starts them again.'
    Out-Line ('  Undo: ' + (($svcs | ForEach-Object { "Start-Service -Name '$($_.Name)'" }) -join '; ') + ' (also written to undo.ps1)')
    if (-not (Read-YesNo 'Stop these services now? This takes the site offline.')) { Out-Line 'skipped'; return }
    foreach ($s in $svcs) {
        try {
            Stop-Service -Name $s.Name -Force -ErrorAction Stop
            Add-UndoLine -Line "Start-Service -Name '$($s.Name)'" -Log "stopped service $($s.Name)"
            Out-Ok "stopped $($s.Name)"
        } catch {
            Out-Bad "could not stop $($s.Name): $($_.Exception.Message)"
        }
    }
}

function Invoke-Fixes {
    $bad = @($Installs | Where-Object { $_.status -ne 'PATCHED' })
    if ($bad.Count -eq 0 -or $CompHits.Count -gt 0 -or -not $OnWindows) { return }

    Out-Head 'What you can do'
    Out-Line "Windows PHP is not updated by this script. Download the fixed build for your branch from $DownloadPage"
    Out-Line 'and replace each folder below by hand (stop the web server first, keep php.ini and the ext folder settings):'
    foreach ($i in $bad) {
        $target = $(if ($i.fixedIn) { "fixed in $($i.fixedIn)" } else { $i.detail })
        Out-Line "  $(Split-Path -Parent $i.path)  (PHP $(if ($i.version) { $i.version } else { '?' }), $target)"
    }

    if (-not $Result.isAdmin) {
        Out-Line ''
        Out-Line 'You are not running as Administrator, so no service changes are offered.'
        Out-Line 'If someone else runs this server, send them this message:'
        Out-Line ''
        foreach ($l in (Get-HostMessage)) { Out-Line "  $l" }
        return
    }

    if (-not (Test-Interactive)) {
        if (-not $CheckOnly) { Out-Line 'no interactive console; running check-only, no prompts' }
        return
    }

    foreach ($fix in $FixTable) {
        try {
            if (& $fix.Condition) { & $fix.Apply }
        } catch {
            Out-Bad "fix $($fix.Id) failed: $($_.Exception.Message)"
        }
    }
    if ($script:BackupDir) {
        Out-Line ''
        Out-Line "Changes logged in $script:BackupDir. To undo: powershell -ExecutionPolicy Bypass -File `"$(Join-Path $script:BackupDir 'undo.ps1')`""
    }
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

function Invoke-Main {
    $Result.isAdmin = Test-IsAdmin
    Out-Line "php2shell-check.ps1 $ToolVersion - $($CveIds -join ' / ') - host $([Environment]::MachineName) - $((Get-Date).ToString('yyyy-MM-dd HH:mm'))"
    if (-not $OnWindows) { Out-Warn 'this is not Windows; results below are incomplete. Use php2shell-check.sh on Linux.' }
    if ($OnWindows -and -not $Result.isAdmin) { Out-Line 'not running as Administrator: some processes, IIS config and scheduled tasks may be hidden' }

    try { Invoke-Inventory } catch { Out-Skip "PHP search failed: $($_.Exception.Message)" }

    $branches = New-Object System.Collections.ArrayList
    foreach ($b in $KnownBranches) { [void]$branches.Add($b) }
    foreach ($i in $Installs) {
        if ($i.branch -and ([version]$i.branch) -ge $SupportedFrom -and -not $branches.Contains($i.branch)) { [void]$branches.Add($i.branch) }
    }
    try { Resolve-FixedVersions -Branches $branches } catch { Out-Skip "fixed versions: $($_.Exception.Message)" }

    Out-Head 'PHP on this machine'
    try { Set-InstallStatus } catch { $script:InventoryOk = $false; Out-Skip "patch status: $($_.Exception.Message)" }

    try { Invoke-Exposure } catch { Out-Skip "exposure check failed: $($_.Exception.Message)" }
    try { Invoke-Compromise } catch { Out-Skip "compromise checks failed: $($_.Exception.Message)" }

    $v = Get-Verdict
    Out-Line ''
    Out-Line "VERDICT: $($v.verdict)" $v.color
    foreach ($t in $v.todo) { Out-Line "  - $t" }

    if ($v.code -ne 3) { Invoke-Fixes }

    $Result.installs = @($Installs)
    $Result.exposure.listeners = @($Listeners)
    $Result.exposure.webServers = @($WebServers)
    $Result.exposure.phpSeenOnPorts = @($PhpPorts)
    $Result.compromise.hits = @($CompHits)
    $Result.compromise.warnings = @($CompWarns)
    $Result.skipped = @($Skipped)
    $Result.warnings = @($Warnings)
    $Result.verdict = $v.verdict
    $Result.exitCode = $v.code
    $script:FinalCode = $v.code
}

$FinalCode = 4
$exitCode = 4
try {
    Invoke-Main | Out-Null
    $exitCode = $FinalCode
} catch {
    $Result.verdict = "CHECK INCOMPLETE: $($_.Exception.Message)"
    $Result.exitCode = 4
    $Result['error'] = [string]$_.Exception.Message
    Out-Line "VERDICT: CHECK INCOMPLETE: $($_.Exception.Message)" 'Red'
    $exitCode = 4
}
if ($Json) { Write-Output ($Result | ConvertTo-Json -Depth 5) }
exit $exitCode