#!/usr/bin/env bash
# Local Linux pre-assessment. Rules dated 2026-11-21. Requires Bash 4+.
# Default: show the L1 summary. Use --tsv for the full machine-readable report.
# Inputs: installed DEB/RPM metadata, selected file paths and /proc. Offline.
# Never executes discovered services/binaries or reads application credentials.
# Sources:
# https://ubuntu.com/security/notices/USN-9159-1
# https://ubuntu.com/security/notices/USN-9182-1
# https://security-tracker.debian.org/tracker/DLA-4918-1
# https://security-tracker.debian.org/tracker/DSA-6642-1
# https://security-tracker.debian.org/tracker/DSA-6641-1
# https://security-tracker.debian.org/tracker/DLA-4916-1
# https://security-tracker.debian.org/tracker/CVE-2026-116331
# https://nginx.org/en/security_advisories.html
# https://www.php.net/archive/2026.php
# https://support.cpanel.net/hc/en-us/articles/45152249350423
# https://cloudlinux.com/security/php-november-2026-security-releases
# https://www.postgresql.org/support/security/CVE-2026-116331/
# https://mariadb.com/docs/release-notes/community-server/10.11/10.11.20
# https://dev.mysql.com/community/security/advisories/2026-10-20/
# https://www.oracle.com/security-alerts/cspunov2026.html
# https://www.oracle.com/security-alerts/cpuoct2026.html
# https://github.com/ClickHouse/ClickHouse/pull/115702
# https://thehackernews.com/2026/11/researcher-demonstrates-database-rce.html
if (( BASH_VERSINFO[0] < 4 )); then echo "Bash 4+ required" >&2; exit 2; fi
usage() {
    printf '%s\n' 'Usage: bash server_patch_preassessment.sh [--summary | --tsv]' \
        'Default: human-readable local patch status. --tsv: detailed tab-separated evidence.'
}
mode=${1:---summary}
if (( $# > 1 )); then usage >&2; exit 2; fi
case $mode in --summary|--tsv) ;; --help|-h) usage; exit 0 ;; *) usage >&2; exit 2 ;; esac
export LC_ALL=C PATH=/usr/sbin:/usr/bin:/sbin:/bin
shopt -s nullglob
set -o pipefail
ID=unknown VERSION_ID=unknown
if [[ -r /etc/os-release ]]; then . /etc/os-release; fi
os="${ID:-unknown} ${VERSION_ID:-unknown}"
host=$(hostname 2>/dev/null || uname -n)
stamp=$(date -u +%FT%TZ)
panel=''
[[ -d /usr/local/cpanel ]] && panel=cPanel-WHM
[[ -d /usr/local/CyberCP || -d /usr/local/lscp/cyberpanel ]] && panel="${panel:+$panel+}CyberPanel"
panel=${panel:-none-detected}
declare -A seen counted packages paths duplicates archive_origin php_owners
partial=0
row() {
    # status, component, advisory, item, installed/evidence, target, operator action
    local state=$1 component=$2 field sep='' key
    key=$(printf '%s|' "$@")
    [[ -n ${duplicates[$key]:-} ]] && return 0
    duplicates[$key]=1
    counted[$state]=$(( ${counted[$state]:-0} + 1 ))
    for field in "$host" "$os" "$panel" "$stamp" "$@"; do
        field=${field//[[:cntrl:]]/ }
        printf '%s%s' "$sep" "$field" || exit 1
        sep=$'\t'
    done
    printf '\n' || exit 1
}
gap() {
    partial=1
    row REVIEW Coverage Inventory "$1" "$2" - "$3"
}
# Numeric release tuples only. Callers reject prereleases and vendor suffixes
# before passing the upstream portion here. Package revisions use native dpkg.
at_least() {
    local -a a b
    local i
    IFS=. read -ra a <<< "$1"
    IFS=. read -ra b <<< "$2"
    for ((i=0; i<${#a[@]} || i<${#b[@]}; i++)); do
        (( 10#${a[i]:-0} > 10#${b[i]:-0} )) && return 0
        (( 10#${a[i]:-0} < 10#${b[i]:-0} )) && return 1
    done
    return 0
}
# Classify the installed package itself. A client package is not a DB server.
pkg_component() {
    case "$1" in
        nginx|nginx-core|nginx-full|nginx-light|nginx-extras|nginx-dev|nginx-naxsi|libnginx-mod-stream|ea-nginx|nginx-plus|openresty) echo NGINX ;;
        postgresql|postgresql-server) echo PostgreSQL ;;
        mysql-server|mysql-community-server|mysql-cluster-community-server|mysql-community-server-core|mysql-cluster-community-data-node|mysql-server-core-*) echo MySQL ;;
        mariadb-server|mariadb-server-core|mariadb-server-[0-9]*|mariadb-server-core-*) echo MariaDB ;;
        community-mysql-server|percona-server-server*|percona-xtradb-cluster-server*) echo DB-variant ;;
        clickhouse-server|clickhouse-common-static) echo ClickHouse ;;
        oracle-database-*preinstall*) ;;
        oracle-database-*|oracle-free-*) echo Oracle-DB ;;
        ords|oracle-rest-data-services) echo ORDS ;;
        odoo|odoo-server|odoo[0-9]*) echo Odoo ;;
        apache2|apache2-bin|httpd|httpd-core|ea-apache24) echo Apache ;;
        openlitespeed|litespeed|lsws) echo LiteSpeed ;;
        *)
            if [[ $1 =~ ^postgresql(-[0-9]+|[0-9]+-server)$ ]]; then echo PostgreSQL
            elif [[ $1 =~ ^(mysql-server|mysql-cluster-server)-[0-9]+\.[0-9]+$ ]]; then echo MySQL
            elif [[ $1 =~ ^(php([0-9]+\.[0-9]+)?(-(cli|fpm|cgi|common|core|litespeed|phpdbg|embed|modphp))?|libapache2-mod-php([0-9]+\.[0-9]+)?|lsphp([0-9]+)?(-(common|cli|fpm))?|ea-php[0-9]+-php(-(cli|common|fpm|cgi|litespeed))?|alt-php[0-9]+(-(php-)?(cli|common|fpm|cgi|lsphp))?|cpanel-php[0-9]+(-(cli|common|fpm))?|php[0-9]+-php(-(cli|common|fpm))?)$ ]]; then echo PHP
            fi ;;
    esac
}
declare -A php_fix=([8.2]=8.2.36 [8.3]=8.3.37 [8.4]=8.4.28 [8.5]=8.5.13 [8.6]=8.6.0)
declare -A pg_fix=([14]=14.25 [15]=15.20 [16]=16.16 [17]=17.12 [18]=18.7)
declare -A ch_fix=([26.3]=26.3.32.8 [26.6]=26.6.5.55 [26.7]=26.7.7.30 [26.8]=26.8.3.41)
declare -A nginx_usn=([14.04]=1.4.6-1ubuntu3.9+esm10 [16.04]=1.10.3-0ubuntu0.16.04.5+esm11 [18.04]=1.14.0-0ubuntu1.11+esm6 [20.04]=1.18.0-0ubuntu1.7+esm5 [22.04]=1.18.0-6ubuntu14.23 [24.04]=1.24.0-2ubuntu7.20 [26.04]=1.28.3-2ubuntu1.13 [26.10]=1.30.4-7ubuntu1.2)
declare -A nginx_next=([14.04]=1.4.6-1ubuntu3.9+esm11 [16.04]=1.10.3-0ubuntu0.16.04.5+esm12 [18.04]=1.14.0-0ubuntu1.11+esm7 [20.04]=1.18.0-0ubuntu1.7+esm6 [22.04]=1.18.0-6ubuntu14.24 [24.04]=1.24.0-2ubuntu7.21 [26.04]=1.28.3-2ubuntu1.14 [26.10]=1.30.4-7ubuntu1.3)
# Exact installed version must also appear in this release's locally cached
# official archive metadata before Ubuntu package thresholds can decide a row.
read_archive_origins() {
    [[ -z ${DPKG_ADMINDIR:-} || $DPKG_ADMINDIR == /var/lib/dpkg ]] || return 0
    [[ ( $ID == ubuntu || $ID == debian ) && -x /usr/bin/python3 ]] || return 0
    local n a v
    while IFS='|' read -r n a v; do
        [[ -n $n && -n $v ]] && archive_origin["$n|$a|$v"]=1
    done < <(/usr/bin/python3 -IB - "$ID" "${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}" 2>/dev/null <<'PY'
import apt
import apt_pkg
apt_pkg.init_config()
apt_pkg.config.set("Dir::Cache::pkgcache", "")
apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
import sys
distro, codename = sys.argv[1:]
cache = apt.Cache(memonly=True)
sources = {"nginx", "php8.2", "php8.4", "postgresql-15", "postgresql-17"}
acceptable = {"Debian"} if distro == "debian" else {"Ubuntu", "UbuntuESM", "UbuntuESMApps", "UbuntuESMInfra"}
for pkg in cache:
    if not pkg.name.startswith(("nginx", "libnginx", "php8.", "libapache2-mod-php", "postgresql-")):
        continue
    v = pkg.installed
    if v is None or v.source_name not in sources:
        continue
    origins = [o for o in v.origins if o.site]
    files = [f for f, index in v._cand.file_list if f.site]
    if (codename and files and origins and all(o.trusted and o.origin in acceptable for o in origins)
            and all(f.codename == codename or f.codename.startswith(codename + "-") for f in files)):
        print("|".join((pkg.name.split(":")[0], v.architecture, v.version)))
PY
)
}
archive_row() {
    local ref=$1 threshold=$2 action="Update this $ID package through its security repository."
    [[ $threshold == *+esm* ]] && action="Check Ubuntu Pro/Legacy entitlement and update through the matching ESM repository."
    if [[ -z ${archive_origin["$name|$arch|$full"]:-} ]]; then
        local comparison="at or above"
        dpkg --compare-versions "$full" lt "$threshold" && comparison="below"
        row REVIEW "$comp" "$ref" "$item" "$full" "$threshold ($ID only)" "Installed version is $comparison the $ID threshold. Verify its origin and the applicable vendor fix using local repository records."
    elif dpkg --compare-versions "$full" ge "$threshold"; then
        row MEETS_BASELINE "$comp" "$ref" "$item" "$full" "$threshold" "Installed package meets this notice."
    else
        row PATCH "$comp" "$ref" "$item" "$full" "$threshold" "$action"
    fi
}
assess() {
    local kind=$1 name=$2 arch=$3 full=$4 raw=$5 vendor=$6
    local comp item base branch major threshold='' ref='' action='' status=VERIFY_BACKPORT
    local numeric='^([0-9]+(\.[0-9]+){1,3})([-+].*)?$'
    case "${name,,}" in
        php*|ea-*|alt-*|lsphp*|cpanel-*|nginx*|libnginx*|libapache*|postgres*|mysql*|mariadb*|community-mysql*|percona*|clickhouse*|oracle*|ords|odoo*|apache*|httpd*|openresty|openlitespeed|litespeed|lsws) ;;
        *) return 0 ;;
    esac
    if [[ $name == postgresql ]]; then
        row INFO DB-client-or-meta Inventory "$kind:$name:$arch" "$full" - "Look for a separate PostgreSQL server package."
        return 0
    fi
    comp=$(pkg_component "${name,,}")
    if [[ $kind == deb && $vendor =~ ^php[0-9]+[.][0-9]+$ ]]; then comp=PHP; fi
    [[ -n $comp ]] || return 0
    item="$kind:$name:$arch"
    packages[$name]=$comp
    seen[$comp]=1
    raw=${raw#*:}
    if [[ $kind == deb && $ID == debian && $full != *pgdg* ]]; then
        case "$VERSION_ID/$vendor/$comp" in
            12/php8.2/PHP) archive_row DLA-4916-1 '8.2.36-1~deb12u1'; return ;;
            13/php8.4/PHP) archive_row DSA-6641-1 '8.4.28-1~deb13u1'; return ;;
            12/nginx/NGINX) archive_row DLA-4918-1 '1.22.1-9+deb12u11'; return ;;
            13/nginx/NGINX) archive_row DSA-6642-1 '1.26.3-3+deb13u11'; return ;;
            12/postgresql-15/PostgreSQL) archive_row DLA-4905-1 '15.20-0+deb12u1'; return ;;
            13/postgresql-17/PostgreSQL) archive_row DSA-6625-1 '17.12-0+deb13u1'; return ;;
        esac
    fi
    case $comp in
        Oracle-DB) row REVIEW "$comp" CVE-2026-114819 "$item" "$full" '19.3–19.32 / 21.3–21.24 / 23.4.0–23.26.3' "DBA: check Oracle Text, each Oracle Home RU/one-off inventory and database SQL patch registry against the November update."; return ;;
        ORDS) row REVIEW "$comp" CVE-2026-91609 "$item" "$full" '24.2.0–26.2.1 affected' "Check deployed ORDS WAR or standalone build against the October CPU, including deployments separate from the database."; return ;;
        DB-variant) row REVIEW "$comp" CVE-2026-101786 "$item" "$full" 'Oracle MySQL advisory' "Confirm applicability and backports with this fork or distribution."; return ;;
        Odoo|Apache|LiteSpeed) row INFO "$comp" Inventory "$item" "$full" - "Stack context for the database or PHP handler checks."; return ;;
        NGINX)
            if [[ $kind == deb && $ID == ubuntu && -n ${nginx_usn[$VERSION_ID]:-} && $vendor == nginx && $name != ea-* ]]; then
                # nginx-dev appears only on the three newest releases of the original
                # notice. The follow-up lists stream only on four release lines.
                local original=1 follow=1
                case $name in
                    nginx-dev) follow=0; case $VERSION_ID in 24.04|26.04|26.10) ;; *) original=0 ;; esac ;;
                    libnginx-mod-stream) original=0; case $VERSION_ID in 18.04|20.04|22.04|24.04) ;; *) follow=0 ;; esac ;;
                    nginx-naxsi) original=0; [[ $VERSION_ID == 14.04 ]] || follow=0 ;;
                esac
                (( original )) && archive_row USN-9159-1 "${nginx_usn[$VERSION_ID]}"
                (( follow )) && archive_row USN-9182-1 "${nginx_next[$VERSION_ID]}"
                (( original || follow )) || row INFO "$comp" Inventory "$item" "$full" - "Consult the runtime package rows for this release."
                return 0
            fi ;;
    esac
    case $comp in
        PHP) ref=PHP-2026-11-19; action="Confirm the November release with the PHP package supplier for this handler." ;;
        PostgreSQL) ref=CVE-2026-116331; action="Check the database server build and the supplier's backport for this CVE." ;;
        MariaDB) ref=MariaDB-Q4-2026; action="Verify the MariaDB Community Server update for this branch." ;;
        MySQL) ref=CVE-2026-101786; action="Check the October CPU for the installed server edition." ;;
        ClickHouse) ref=ClickHouse-PR-115702; action="Match the server build to the official backport or vendor equivalent." ;;
        NGINX) ref=NGINX-2026-11; action="Check this provider's NGINX advisory, including any backports." ;;
    esac
    if [[ ! $raw =~ $numeric || ${raw,,} =~ (alpha|beta|preview|snapshot|(^|[^a-z])rc[0-9]) ]]; then
        row REVIEW "$comp" "$ref" "$item" "$full" - "$action Version cannot be mapped automatically."; return
    fi
    base=${raw%%[-+]*}
    local tail=${base#*.}
    major=${base%%.*}
    branch="$major.${tail%%.*}"
    case $comp in
        MariaDB)
            case $branch in
                10.11) threshold=10.11.20 ;; 11.4) threshold=11.4.14 ;;
                11.8) threshold=11.8.10 ;; 12.3) threshold=12.3.4 ;;
            esac
            if [[ $kind == deb && $raw =~ ^[0-9]+[.][0-9]+[.][0-9]+[+]maria~(ubu|deb)[0-9]+$ ]]; then
                status=PATCH
            elif [[ $kind == rpm && $name == MariaDB-* && ${vendor,,} == *mariadb* ]]; then
                status=PATCH
            fi ;;
        PHP)
            threshold=${php_fix[$branch]:-}
            # CloudLinux alt-PHP legacy builds keep their upstream version.
            # These release numbers apply only to the indicated vendor and OS.
            if [[ $kind == rpm && $name == alt-php* && $ID == cloudlinux &&
                  ${VERSION_ID%%.*} =~ ^[789]$ && ${vendor,,} == *cloudlinux* &&
                  $full =~ ^0:([0-9.]+)-([0-9]+)([.]el[789]([.][a-zA-Z0-9]+)*)?$ ]]; then
                local altversion=${BASH_REMATCH[1]} altrel=${BASH_REMATCH[2]} floor=''
                case $altversion in
                    5.6.40) floor=152 ;; 7.3.33) floor=86 ;; 7.4.33) floor=84 ;;
                    8.0.30) floor=72 ;; 8.1.34) floor=43 ;;
                esac
                if [[ -n $floor ]]; then
                    local result=PATCH
                    (( 10#$altrel >= floor )) && result=MEETS_BASELINE
                    row "$result" PHP "$ref" "$item" "$full" "$altversion-$floor (CloudLinux alt-PHP)" "Use the CloudLinux alt-PHP security build for this OS and branch."
                    return
                fi
            fi
            if [[ -z $threshold && $name == ea-php74-* ]]; then
                # cPanel documents this changelog marker for its November EA4
                # backport. Only apply it to this vendor/branch and exact build.
                local marker=CVE-2026-129289 confirmed=0
                if [[ $kind == rpm && ${vendor,,} == *cpanel* ]]; then
                    rpm -q --changelog "$name-${full#*:}.$arch" 2>/dev/null |
                        awk -v m="$marker" 'index($0,m){found=1} END{exit !found}' && confirmed=1
                elif [[ $kind == deb && $vendor == ea-php74* && -r /usr/share/doc/$name/changelog.Debian.gz ]]; then
                    gzip -cd -- "/usr/share/doc/$name/changelog.Debian.gz" 2>/dev/null |
                        awk -v m="$marker" 'index($0,m){found=1} END{exit !found}' && confirmed=1
                fi
                if (( confirmed )); then
                    row MEETS_BASELINE PHP "$ref" "$item" "$full" "cPanel EA4 changelog $marker" "Installed build carries the vendor-documented November fix marker."
                    return
                fi
                row REVIEW PHP "$ref" "$item" "$full" 'EA 7.4 vendor backport' "Verify cPanel's November changelog marker CVE-2026-129289 or the full CloudLinux fixed RPM release."; return
            fi
            if [[ -n $threshold && $name == ea-* && $ID != cloudlinux && ( ${vendor,,} == *cpanel* || ( $kind == deb && $vendor == ea-* ) ) ]]; then
                status=PATCH
            fi ;;
        PostgreSQL)
            threshold=${pg_fix[$major]:-}
            [[ $full == *pgdg* || ${vendor,,} == *postgresql*global* ]] && status=PATCH ;;
        MySQL)
            if [[ ! $base =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
                row REVIEW MySQL "$ref" "$item" "$full" '26.7.0–26.7.1 affected' "$action"; return
            fi
            if [[ $base == 26.7.0 || $base == 26.7.1 ]]; then
                [[ ${vendor,,} == *oracle* || $name == mysql-community-* || $name == mysql-cluster-community-* ]] && status=PATCH
                row "$status" "$comp" "$ref" "$item" "$full" 'October CPU covering 26.7.0–26.7.1' "$action Use a vendor-fixed release."; return
            fi
            row OUTSIDE_LIST "$comp" "$ref" "$item" "$full" '26.7.0–26.7.1 affected' "Outside Oracle's listed range for this CVE."; return ;;
        ClickHouse)
            threshold=${ch_fix[$branch]:-}
            if at_least "$branch" 26.9; then threshold=26.9; fi
            [[ ${vendor,,} == *clickhouse* ]] && status=PATCH ;;
        NGINX)
            if [[ $name != openresty && $name != nginx-plus ]]; then
                case $branch in
                    1.30) threshold=1.30.7 ;; 1.31) threshold=1.31.9 ;;
                    *) action="$action Upstream fixed lines are 1.30.7 and 1.31.9." ;;
                esac
            fi
            [[ $name == ea-nginx && $branch == 1.31 ]] && status=PATCH ;;
    esac
    if [[ -z $threshold ]]; then
        row REVIEW "$comp" "$ref" "$item" "$full" 'vendor build required' "$action Check legacy support, forks or unlisted branches."
    elif at_least "$base" "$threshold"; then
        row MEETS_BASELINE "$comp" "$ref" "$item" "$full" "$threshold" "Installed version meets the branch baseline. Confirm deployment in the serving instance."
    else
        row "$status" "$comp" "$ref" "$item" "$full" "$threshold" "$action ${status_message[$status]}"
    fi
}
declare -A status_message=([PATCH]='Schedule the vendor update.' [VERIFY_BACKPORT]='Below upstream baseline. Obtain vendor fix evidence or schedule an update.')
collect() {
printf 'host\tos\tpanel\tscan_utc\tstatus\tcomponent\tadvisory\titem\tinstalled_or_evidence\ttarget_or_scope\taction\n' || exit 1
read_archive_origins
readers=0
if command -v dpkg-query >/dev/null && [[ -e ${DPKG_ADMINDIR:-/var/lib/dpkg}/status ]]; then
    ((readers++))
    if data=$(dpkg-query -W -f='${db:Status-Status}|${Package}|${Architecture}|${Version}|${source:Package}\n'); then
        [[ -n $data ]] || gap dpkg "empty inventory" "Check the active package database."
        while IFS='|' read -r state name arch version sourcepkg; do
            [[ $state == installed ]] && assess deb "$name" "$arch" "$version" "$version" "$sourcepkg"
        done <<< "$data"
    else gap dpkg 'query failed' 'Check dpkg database access and rerun.'; fi
fi
if command -v rpm >/dev/null && { [[ -e /var/lib/rpm/Packages || -e /var/lib/rpm/rpmdb.sqlite || -e /usr/lib/sysimage/rpm/rpmdb.sqlite ]] || (( ! readers )); }; then
    ((readers++))
    if data=$(rpm -qa --qf '%{NAME}|%{ARCH}|%{EPOCH}|%{VERSION}|%{RELEASE}|%{VENDOR}\n') && [[ -n $data ]]; then
        while IFS='|' read -r name arch epoch version release vendor; do
            [[ $epoch == '(none)' ]] && epoch=0
            assess rpm "$name" "$arch" "$epoch:$version-$release" "$version" "$vendor"
        done <<< "$data"
    else gap rpm 'empty or failed query' 'Check rpm database access and rerun.'; fi
fi
unset data
(( readers )) || gap packages 'no supported DEB/RPM database' 'Inventory package versions with the platform owner.'

# Resolve a file to an already-assessed package; a second, unpackaged copy on the
# same host still gets its own review row. Only OS package tools are executed.
path_check() {
    local comp=$1 path=$2 real owner='' match='' rec ref target
    [[ -e $path ]] || return 0
    real=$(readlink -f -- "$path") || real=$path
    [[ -n ${paths["$comp|$real"]:-} ]] && return 0
    paths["$comp|$real"]=1
    if command -v dpkg-query >/dev/null; then
        rec=$(dpkg-query -S -- "$real" 2>/dev/null)
        owner=${rec%%: /*}
        owner=${owner%%:*}
        if [[ -n $owner ]]; then
            if [[ $comp == MySQL ]]; then
                case ${packages[$owner]:-} in MariaDB|DB-variant) comp=${packages[$owner]} ;; esac
            fi
            [[ ${packages[$owner]:-} == "$comp" ]] && match=$owner
        fi
    fi
    if [[ -z $match ]] && command -v rpm >/dev/null; then
        owner=$(rpm -qf --qf '%{NAME}' -- "$real" 2>/dev/null)
        if [[ -n $owner ]]; then
            if [[ $comp == MySQL ]]; then
                case ${packages[$owner]:-} in MariaDB|DB-variant) comp=${packages[$owner]} ;; esac
            fi
            [[ ${packages[$owner]:-} == "$comp" ]] && match=$owner
        fi
    fi
    seen[$comp]=1
    if [[ $comp == PHP && -n $match ]]; then php_owners[$real]=$match; fi
    if [[ -n $match ]]; then
        row INFO "$comp" Runtime-path "$real" "owner=$match" - "See this package's assessment."
    elif [[ $comp == Apache || $comp == LiteSpeed || $comp == Odoo ]]; then
        row INFO "$comp" Runtime-path "$real" present - "Stack context. Check its PHP handler or database separately."
    else
        case $comp in
            PHP) ref=PHP-2026-11-19; target="8.2.36 / 8.3.37 / 8.4.28 / 8.5.13 or vendor backport" ;;
            PostgreSQL) ref=CVE-2026-116331; target="14.25 / 15.20 / 16.16 / 17.12 / 18.7 or vendor backport" ;;
            MariaDB) ref=MariaDB-Q4-2026; target="Check the MariaDB branch and vendor build" ;;
            MySQL|DB-variant) ref=CVE-2026-101786; target="Oracle MySQL 26.7.0–26.7.1 affected; check forks separately" ;;
            NGINX) ref=NGINX-2026-11; target="1.30.7 / 1.31.9 or vendor backport" ;;
            ClickHouse) ref=ClickHouse-PR-115702; target="26.9+ or 26.8.3.41 / 26.7.7.30 / 26.6.5.55 / 26.3.32.8" ;;
            Oracle-DB) ref=CVE-2026-114819; target="Verify Oracle Text RU and one-offs against November CSPU" ;;
            ORDS) ref=CVE-2026-91609; target="24.2.0–26.2.1 affected; check deployed ORDS build" ;;
            *) ref=Runtime-path; target="vendor build required" ;;
        esac
        row REVIEW "$comp" "$ref" "$real" 'no assessed owner' "$target" "Identify the deployed build and update channel for this copy. Compare with the component advisory."
    fi
}
for p in /usr/bin/php /usr/bin/php[0-9]* /usr/sbin/php-fpm* /usr/local/bin/php /usr/local/sbin/php-fpm \
    /usr/local/libexec/apache*/libphp*.so /usr/lib*/httpd/modules/libphp*.so /usr/lib/apache2/modules/libphp*.so \
    /opt/cpanel/ea-php*/root/usr/{bin/php,sbin/php-fpm,bin/lsphp} /opt/alt/php*/usr/{bin/php,bin/lsphp,sbin/php-fpm} \
    /usr/local/lsws/{fcgi-bin/lsphp*,lsphp*/bin/{php,lsphp}} /usr/local/lscp/fcgi-bin/lsphp* /usr/bin/lsphp* /usr/local/lsws/admin/fcgi-bin/admin_php \
    /usr/local/cpanel/3rdparty/{bin/php,bin/php-cgi,php*/bin/php,php/*/bin/php,sbin/php-fpm}; do
    [[ -f $p ]] && path_check PHP "$p"
done

# A panel alias can point at a site handler or a separate copy. Preserve the
# configured path, even when the resolved binary already appeared in inventory.
panel_php_path() {
    local role=$1 path=$2 real evidence
    [[ -f $path || -L $path ]] || return 0
    real=$(readlink -f -- "$path") || real=$path
    seen[PHP]=1
    if [[ ! -f $path || ! -x $path ]]; then
        row REVIEW PHP "$role" "$path" 'missing or non-executable target' "$real" "Check the panel PHP handler path."
        return
    fi
    path_check PHP "$path"
    evidence="unverified binary"
    [[ -n ${php_owners[$real]:-} ]] && evidence="owner=${php_owners[$real]}"
    row INFO PHP "$role" "$path" "$evidence" "$real" "Use the assessment for the package owning the resolved target."
}
for p in /usr/local/lscp/fcgi-bin/lsphp*; do panel_php_path CyberPanel-PHP "$p"; done
panel_php_path LiteSpeed-admin-PHP /usr/local/lsws/admin/fcgi-bin/admin_php
for p in /usr/local/cpanel/3rdparty/{bin/php,bin/php-cgi,php*/bin/php,php/*/bin/php,sbin/php-fpm}; do
    panel_php_path WHM-internal-PHP "$p"
done
for p in /usr/sbin/nginx /usr/local/{nginx/sbin/nginx,openresty/nginx/sbin/nginx} /opt/cpanel/ea-nginx/root/usr/sbin/nginx; do path_check NGINX "$p"; done
for p in /usr/{local/pgsql/bin,pgsql-*/bin,lib/postgresql/*/bin,bin}/postgres; do path_check PostgreSQL "$p"; done
for p in /usr/{sbin,libexec,local/mysql/bin}/mysqld /usr/{sbin,libexec}/mariadbd; do
    [[ -e $p ]] || continue
    r=$(readlink -f -- "$p")
    case "$r" in *mariadb*) path_check MariaDB "$p" ;; *percona*) path_check DB-variant "$p" ;; *) path_check MySQL "$p" ;; esac
done
for p in /usr/bin/clickhouse{,-server} /usr/local/bin/clickhouse{,-server}; do path_check ClickHouse "$p"; done
for p in /usr/local/lsws/bin/{lshttpd,openlitespeed,litespeed}; do path_check LiteSpeed "$p"; done
for p in /usr/sbin/{apache2,httpd} /usr/local/apache/bin/httpd; do path_check Apache "$p"; done
for p in /usr/bin/odoo /opt/odoo*/{odoo-bin,odoo/odoo-bin,server/odoo-bin} /etc/odoo/odoo.conf /etc/odoo.conf; do path_check Odoo "$p"; done
for p in /opt/oracle/product/*/*/bin/oracle /u01/app/oracle/product/*/*/bin/oracle; do path_check Oracle-DB "$p"; done
for p in /opt/{ords,oracle/ords}/{bin/ords,ords.war} /usr/{bin/ords,local/bin/ords} /var/lib/tomcat*/webapps/ords{,.war}; do path_check ORDS "$p"; done
if [[ -s /etc/oratab && -r /etc/oratab ]]; then
    while IFS=: read -r sid dbhome remainder; do
        [[ $sid == \#* || $dbhome != /* ]] && continue
        path_check Oracle-DB "$dbhome/bin/oracle"
    done < /etc/oratab
fi
declare -A active
if [[ ! -d /proc/1 ]]; then
    gap processes '/proc unavailable' 'Verify the running instances separately.'
elif (( EUID != 0 )); then
    gap processes 'non-root scan' 'Use a privileged local inventory to resolve hidden process executables and loaded PHP modules.'
fi
for proc in /proc/[0-9]*; do
    IFS= read -r comm 2>/dev/null < "$proc/comm" || continue
    case $comm in
        nginx*|openresty*) comp=NGINX ;;
        php*|lsphp*|ea-php*) comp=PHP ;;
        postgres|postmaster) comp=PostgreSQL ;;
        mysqld*) comp=MySQL ;;
        mariadbd*) comp=MariaDB ;;
        clickhouse*) comp=ClickHouse ;;
        ora_pmon_*|oracle*) comp=Oracle-DB ;;
        ords) comp=ORDS ;;
        java)
            # Match an ORDS artifact token only. Never print command-line arguments.
            grep -azEq '(^|/)(ords[.]war|ords(-launcher)?[.]jar)$|^oracle[.]dbtools[.]' "$proc/cmdline" 2>/dev/null || continue
            comp=ORDS ;;
        odoo*|openerp*) comp=Odoo ;;
        python*|gunicorn*)
            grep -azEq '(^|/)(odoo(-bin)?|openerp-server)$' "$proc/cmdline" 2>/dev/null || continue
            comp=Odoo ;;
        lshttpd|litespeed|openlitespeed) comp=LiteSpeed ;;
        apache2|httpd) comp=Apache ;;
        *) continue ;;
    esac
    seen[$comp]=1
    exe=$(readlink -- "$proc/exe" 2>/dev/null) || {
        [[ -d $proc ]] && gap "$comp process" 'executable unreadable' 'Verify the running service build with the host owner.'
        continue
    }
    if [[ $exe == *' (deleted)' ]]; then
        row RESTART_REVIEW "$comp" Running-process "$exe" 'deleted executable still running' - "Identify the service or cluster and plan a controlled restart after validating the installed build."
        continue
    fi
    if [[ ! "$proc/root$exe" -ef "$exe" || ! "$proc/exe" -ef "$exe" || ! "$proc/root" -ef / ]]; then
        row REVIEW "$comp" Isolated-runtime "$exe" 'different root or executable' - "Assess this container, chroot or workload using its own package inventory."
        continue
    fi
    if [[ $comp == Apache ]]; then
        # A graceful restart can leave older workers with a deleted PHP module.
        if [[ -r "$proc/maps" ]]; then
            while IFS= read -r module; do
                [[ -n $module ]] || continue
                if [[ $module == *' (deleted)' ]]; then
                    row RESTART_REVIEW PHP Apache-module "$module" 'deleted module still mapped' - "Confirm package update and plan a full Apache worker restart."
                else path_check PHP "$module"; fi
            done < <(awk '/\/libphp[^ /]*\.so( \(deleted\))?$/ {print substr($0,index($0,"/"))}' "$proc/maps" 2>/dev/null)
        fi
    fi
    active["$comp|$exe"]=1
    case $comp in Odoo|ORDS) ;; *) path_check "$comp" "$exe" ;; esac
done
for k in "${!active[@]}"; do
    row INFO "${k%%|*}" Running-process "${k#*|}" running - "Process observed in the local root."
done
if [[ -n ${seen[ORDS]:-} ]]; then
    row REVIEW ORDS CVE-2026-91609 'deployed ORDS application' 'deployment build unverified' '24.2.0–26.2.1 affected' "Match each standalone or servlet deployment to its actual ORDS build and the October CPU."
fi
if [[ -n ${seen[Odoo]:-} ]]; then
    row REVIEW Odoo CVE-2026-116331 'Odoo database dependency' 'backend identity unverified' 'each PostgreSQL primary and replica' "Match each Odoo deployment to its actual DB host or managed service. Attach the server or provider assessment."
fi
if [[ $panel == *cPanel* ]]; then
    row REVIEW PHP PHP-2026-11-19 'WHM internal PHP and site handlers' 'panel detected' 'internal PHP plus each assigned EA4/alt-PHP handler' "Match WHM internal runtime to cPanel's branch bulletin. Reconcile MultiPHP Manager and PHP Selector assignments with package rows."
fi
if [[ $panel == *CyberPanel* || -n ${seen[LiteSpeed]:-} ]]; then
    row REVIEW PHP PHP-2026-11-19 'LiteSpeed PHP handlers' 'handler assignments unverified' 'each vhost and external application' "Match each configured LSAPI executable to its installed LSPHP build, including custom paths."
fi
if [[ -d /var/lib/docker || -S /var/run/docker.sock || -S /run/containerd/containerd.sock || -d /var/lib/containers/storage || -d /etc/kubernetes ]]; then
    row REVIEW Containers Inventory 'container runtime indicators' present 'running workloads and deployable images' "Assess the image digest and package inventory for each workload, including stopped workloads that can return."
fi
for comp in PHP NGINX PostgreSQL MySQL MariaDB ClickHouse Oracle-DB ORDS Apache LiteSpeed Odoo; do
    if [[ -z ${seen[$comp]:-} ]]; then
        row NO_LOCAL_EVIDENCE "$comp" Inventory 'host inventory' - - "No match in inspected packages, common paths or visible processes. Check external or custom deployments where relevant."
    fi
done
row INFO Coverage Inventory 'local Linux namespace' 'rules 2026-11-21' - "Host packages, known paths and visible processes only. Reconcile remote DBs, custom installations, images and service assignments with fleet inventory."
row INFO Coverage Completion 'end of report' "partial=$partial" - "A complete capture contains this final row. REVIEW rows require operator follow-up."
if [[ $mode == --tsv ]]; then
printf '%s: %d PATCH, %d VERIFY_BACKPORT, %d REVIEW, %d RESTART_REVIEW; collection_partial=%d\n' \
    "$host" "${counted[PATCH]:-0}" "${counted[VERIFY_BACKPORT]:-0}" "${counted[REVIEW]:-0}" "${counted[RESTART_REVIEW]:-0}" "$partial" >&2
fi
}

summary() {
    awk -F '\t' '
    function php_family(name) {
        if (name ~ /^(ea-php|.*\/opt\/cpanel\/ea-php)/) return "WHM EA-PHP"
        if (name ~ /^(alt-php|.*\/opt\/alt\/php)/) return "CloudLinux alt-PHP"
        if (name ~ /^(cpanel-php|.*\/cpanel\/3rdparty\/)/) return "WHM internal PHP"
        if (name ~ /\/lscp\/fcgi-bin\//) return "CyberPanel handler PHP"
        if (name ~ /(^lsphp|\/lsws\/)/) return "LiteSpeed PHP (LSPHP)"
        if (name ~ /^php[0-9]+-php/) return "Remi PHP"
        return "System PHP"
    }
    function component(c) {
        if (c == "Oracle-DB") return "Oracle Database"
        if (c == "MySQL") return "Oracle MySQL Server"
        if (c == "MariaDB") return "MariaDB Server"
        if (c == "LiteSpeed") return "LiteSpeed Web Server"
        if (c == "DB-variant") return "MySQL variant"
        if (c == "ORDS") return "Oracle REST Data Services"
        return c
    }
    function record(key, label, status, build, detail) {
        if (!(key in index_seen)) { index_seen[key]=1; ordered[++rows]=key }
        # The highest priority finding determines the displayed result.
        # For two Ubuntu NGINX notices at the same priority prefer the follow-up.
        if (!(key in state) || rank[status] > rank[state[key]] ||
              (rank[status] == rank[state[key]] && current_ref == "USN-9182-1")) {
            title[key]=label; state[key]=status; version[key]=build; note[key]=detail
        }
    }
    function extra(message) {
        if (!(message in notes_seen)) { notes_seen[message]=1; notes[++nnotes]=message }
    }
    function print_row(key) {
        printf "%-*s  %-15s  %-*s  %s\n", width, title[key], state[key], vwidth, version[key], note[key]
    }
    BEGIN {
        rank["Need to patch"]=6; rank["Restart review"]=5; rank["Needs review"]=4
        rank["Patched"]=3; rank["Not affected"]=2; rank["Installed"]=1
        status_name["PATCH"]="Need to patch"; status_name["MEETS_BASELINE"]="Patched"
        status_name["VERIFY_BACKPORT"]="Needs review"; status_name["REVIEW"]="Needs review"
        status_name["RESTART_REVIEW"]="Restart review"; status_name["OUTSIDE_LIST"]="Not affected"
    }
    NR==1 { next }
    NF!=11 { invalid=1; next }
    {
        host=$1; os=$2; panel=$3; stamp=$4; st=$5; c=$6; current_ref=$7
        item=$8; evidence=$9; target=$10; action=$11
        if (c=="Coverage") {
            if (current_ref=="Completion") { finished=1; partial=(evidence!="partial=0") }
            if (st=="REVIEW") {
                extra(item ": " evidence ". " action)
                if (item ~ / process$/) {
                    sub(/ process$/, "", item)
                    record("unreadable" SUBSEP item,component(item),"Needs review","-","Running process could not be identified.")
                }
            }
            next
        }
        if (c=="DB-client-or-meta") next
        if (c=="Containers") { extra(action); next }
        if (st=="NO_LOCAL_EVIDENCE") { absences[++missing]=c; next }
        if (item=="WHM internal PHP and site handlers" || item=="LiteSpeed PHP handlers") {
            panel_check=1; extra(action); next
        }
        if (current_ref=="CyberPanel-PHP" || current_ref=="WHM-internal-PHP" || current_ref=="LiteSpeed-admin-PHP") {
            alias[++aliases]=item; role[item]=(current_ref=="CyberPanel-PHP" ? "CyberPanel handler PHP" : (current_ref=="LiteSpeed-admin-PHP" ? "LiteSpeed admin PHP" : "WHM internal PHP handler"))
            owner[item]=evidence; sub(/^owner=/,"",owner[item]); dest[item]=target
            next
        }
        label=component(c); key=c; result=status_name[st]; build="-"; detail=""
        pkg=(item ~ /^(deb|rpm):/)
        if (pkg) {
            split(item, seg, ":"); name=seg[2]; build=evidence
            if (c=="PHP") {
                label=php_family(name)
                key=label SUBSEP build
                # Resolve panel symlinks against the exact owning package.
                if (name in ownerkey && ownerkey[name]!=key) ambiguous[name]=1
                ownerkey[name]=key
                handler=""
                if (name ~ /-fpm$/) handler="FPM"
                else if (name ~ /-cli$/) handler="CLI"
                else if (name ~ /(-litespeed|-lsphp)$/ || name ~ /^lsphp[0-9]+$/) handler="LSAPI"
                else if (name ~ /^libapache2-mod-/) handler="Apache module"
                else if (name ~ /-cgi$/) handler="CGI"
                if (handler!="" && !((key SUBSEP handler) in handlers_seen)) {
                    handlers_seen[key SUBSEP handler]=1
                    handlers[key]=handlers[key] (handlers[key]!="" ? "/" : "") handler
                }
            }
        }
        if (st=="INFO") {
            if (c!="LiteSpeed" && c!="Apache" && c!="Odoo") next
            if (!pkg && current_ref!="Runtime-path" && current_ref!="Running-process") next
            result="Installed"; detail=(c=="Odoo" ? "Check the PostgreSQL backend." : (c=="LiteSpeed" ? "Web server detected. Security build not assessed." : "Check the PHP handlers listed separately."))
        } else if (st=="PATCH") detail=name " | target " target
        else if (st=="MEETS_BASELINE") detail="Meets " target
        else if (st=="VERIFY_BACKPORT") detail=name " | confirm vendor fix (upstream " target ")"
        else if (st=="OUTSIDE_LIST") detail="Outside the affected range."
        else if (st=="RESTART_REVIEW") {
            key=c SUBSEP item; detail=item " | check running workers"
            if (c=="PHP") label=php_family(item)
        } else if (st=="REVIEW") {
            if (pkg) detail=name " | " (target=="-" ? "verify vendor build" : target)
            else if (c=="Odoo") { label="Odoo database connection"; key=label; detail="Verify the PostgreSQL host used by Odoo." }
            else if (item ~ /^\//) {
                if (c=="PHP") label=php_family(item)
                key=c SUBSEP item; detail=item " | verify this build"
            } else detail=action
        }
        if (result!="") record(key,label,result,build,detail)
    }
    END {
        if (!finished || invalid) { print "Assessment incomplete. Rerun before using the results." > "/dev/stderr"; exit 1 }
        for (i=1;i<=aliases;i++) {
            path=alias[i]; k=ownerkey[owner[path]]; label=role[path]
            if (k in state && !ambiguous[owner[path]]) {
                record("alias" SUBSEP path,label,state[k],version[k],path " -> " owner[path])
            } else record("alias" SUBSEP path,label,"Needs review","-",path " -> " dest[path])
        }
        for (i=1;i<=missing;i++) {
            c=absences[i]
            if (partial || (c=="PHP" && panel_check))
                record(c,component(c),"Needs review","-","No local match; coverage incomplete.")
            else record(c,component(c),"Not installed","-","")
        }
        for (k in handlers) title[k]=title[k] " (" handlers[k] ")"
        width=length("Component"); vwidth=length("Installed build")
        for (i=1;i<=rows;i++) {
            k=ordered[i]; if (length(title[k])>width) width=length(title[k])
            if (length(version[k])>vwidth) vwidth=length(version[k])
        }
        printf "Host %s  |  %s  |  Panel %s  |  %s\n\n",host,os,panel,stamp
        printf "%-*s  %-15s  %-*s  %s\n", width,"Component","Status",vwidth,"Installed build","Details"
        # Actionable findings first. Keep the relative order within each status.
        split("Need to patch|Restart review|Needs review|Patched|Not affected|Installed|Not installed", priorities, /[|]/)
        for (p=1;p<=7;p++)
            for (i=1;i<=rows;i++)
                if (state[ordered[i]]==priorities[p]) print_row(ordered[i])
        if (nnotes) { print "\nFollow-up"; for (i=1;i<=nnotes;i++) print "  - " notes[i] }
        print "\nScope: listed advisories and local installations. Not installed = no match in the locations checked."
        print "Use --tsv for package names, paths, advisories and actions."
    }'
}
if [[ $mode == --tsv ]]; then
    collect
else
    collect | summary
fi