CVE-2026-41940 – WHM & cPanel Authentication Bypass, Checking for Indicators of Compromise

  • Checking using the official cPanel script
  • Checking the access logs
  • How to check the last time WHM was upgraded

Checking using the official cPanel script

The instructions for using the official script are on the cPanel article.

https://support.cpanel.net/hc/en-us/articles/40073787579671-Security-CVE-2026-41940-cPanel-WHM-WP2-Security-Update-04-28-2026

Copy and paste the script into a shell file. Run the script.

Here is a copy of the script for convenience.

#!/bin/bash
# Scan for compromised cPanel/WHM session files.
#
# Each check function inspects a single session file and, if the IOC
# matches, calls report_finding with a severity. report_finding records
# the finding, prints a one-line header, and dumps the session for triage.
# A summary of all findings (grouped by severity) is printed at the end.


# Default paths
SESSIONS_DIR="/var/cpanel/sessions"
ACCESS_LOG="/usr/local/cpanel/logs/access_log"

# Flags
VERBOSE=0
PURGE=0
ASSUME_YES=0

# Parse flags
while [ $# -gt 0 ]; do
    case "$1" in
        --verbose)
            VERBOSE=1
            ;;
        --purge)
            PURGE=1
            ;;
        --yes|-y)
            ASSUME_YES=1
            ;;
        --sessions-dir)
            SESSIONS_DIR="$2"; shift
            ;;
        --access-log)
            ACCESS_LOG="$2"; shift
            ;;
        --help|-h)
            echo "Usage: $0 [--verbose] [--purge [--yes]] [--sessions-dir DIR] [--access-log FILE]"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2
            exit 1
            ;;
    esac
    shift
done

# Findings accumulator. Each entry: "SEVERITY|session_file|short_message"
FINDINGS=()
# Ordered list of unique session files that produced findings.
FINDING_SESSIONS=()
# Parallel array: token value associated with each entry in FINDING_SESSIONS
# (first non-empty token seen for that session).
FINDING_TOKENS=()
# Parallel array: highest severity reported for each session (by index)
FINDING_SEVERITIES=()
COUNT_CRITICAL=0
COUNT_WARNING=0
COUNT_INFO=0
COUNT_ATTEMPT=0

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

# Extract the value of a key=value line from a session file (first match).
# Use: get_field <file> <key>
get_field() {
    local file="$1" key="$2"
    grep "^${key}=" "$file" | head -1 | cut -d= -f2-
}

hr() {
    echo "    ----------------------------------------------------------------"
}

# Dump full contents of a session file plus related context (matching
# pre-auth file, access_log hits for the injected token, file metadata).
# Use: dump_session <session_file> [token_value]
dump_session() {
    local session_file="$1"
    local token_val="$2"
    local session_name preauth_file
    session_name=$(basename "$session_file")
    preauth_file="$SESSIONS_DIR/preauth/$session_name"

    hr
    echo "    SESSION DUMP: $session_file"
    hr
    echo "    File metadata:"
    ls -la "$session_file" 2>/dev/null | sed 's/^/      /'
    echo
    echo "    Full session contents:"
    sed 's/^/      /' "$session_file"
    echo

    if [ -f "$preauth_file" ]; then
        echo "    Matching pre-auth file: $preauth_file"
        ls -la "$preauth_file" 2>/dev/null | sed 's/^/      /'
        echo "    Pre-auth contents:"
        sed 's/^/      /' "$preauth_file"
        echo
    fi

    if [ -n "$token_val" ] && [ -r "$ACCESS_LOG" ]; then
        echo "    Access log hits for token '$token_val':"
        grep -aF -- "$token_val" "$ACCESS_LOG" | sed 's/^/      /' || echo "      (none)"
        echo
    fi
    hr
}

# Record a finding and print a brief header line. The full session dump is
# deferred to print_summary so that multiple findings for the same session
# are grouped together and the session is only dumped once. When the same
# session matches multiple IOCs at different severities, only the highest
# (CRITICAL > WARNING > ATTEMPT > INFO) is kept.
# Use: report_finding <SEVERITY> <session_file> <token_value> <message>
# SEVERITY is one of: CRITICAL, WARNING, ATTEMPT, INFO
report_finding() {
    local severity="$1"
    local session_file="$2"
    local token_val="$3"
    local message="$4"

    # Severity ranking: CRITICAL=3, WARNING=2, ATTEMPT=1, INFO=0
    local sev_rank=0
    case "$severity" in
        CRITICAL) sev_rank=3 ;;
        WARNING)  sev_rank=2 ;;
        ATTEMPT)  sev_rank=1 ;;
        INFO)     sev_rank=0 ;;
    esac

    local i found=0 prev_sev prev_rank
    for i in "${!FINDING_SESSIONS[@]}"; do
        if [ "${FINDING_SESSIONS[$i]}" = "$session_file" ]; then
            found=1
            prev_sev="${FINDING_SEVERITIES[$i]}"
            case "$prev_sev" in
                CRITICAL) prev_rank=3 ;;
                WARNING)  prev_rank=2 ;;
                ATTEMPT)  prev_rank=1 ;;
                INFO)     prev_rank=0 ;;
            esac
            if [ "$sev_rank" -le "$prev_rank" ]; then
                # Existing finding is at least as severe; ignore.
                return
            fi
            # Upgrade in place: replace severity, token, FINDINGS entry,
            # and roll back the previous severity counter so the new one
            # can be incremented below without double-counting.
            FINDING_SEVERITIES[$i]="$severity"
            [ -n "$token_val" ] && FINDING_TOKENS[$i]="$token_val"
            local j
            for j in "${!FINDINGS[@]}"; do
                local entry="${FINDINGS[$j]}"
                local entry_sev="${entry%%|*}"
                local entry_file="${entry#*|}"; entry_file="${entry_file%%|*}"
                if [ "$entry_file" = "$session_file" ] && [ "$entry_sev" = "$prev_sev" ]; then
                    FINDINGS[$j]="${severity}|${session_file}|${message}"
                    break
                fi
            done
            case "$prev_sev" in
                CRITICAL) COUNT_CRITICAL=$((COUNT_CRITICAL - 1)) ;;
                WARNING)  COUNT_WARNING=$((COUNT_WARNING - 1))   ;;
                ATTEMPT)  COUNT_ATTEMPT=$((COUNT_ATTEMPT - 1))   ;;
                INFO)     COUNT_INFO=$((COUNT_INFO - 1))         ;;
            esac
            break
        fi
    done

    if [ "$found" -eq 0 ]; then
        FINDING_SESSIONS+=("$session_file")
        FINDING_TOKENS+=("$token_val")
        FINDING_SEVERITIES+=("$severity")
        FINDINGS+=("${severity}|${session_file}|${message}")
    fi

    case "$severity" in
        CRITICAL) COUNT_CRITICAL=$((COUNT_CRITICAL + 1)) ;;
        WARNING)  COUNT_WARNING=$((COUNT_WARNING + 1))   ;;
        ATTEMPT)  COUNT_ATTEMPT=$((COUNT_ATTEMPT + 1))   ;;
        INFO)     COUNT_INFO=$((COUNT_INFO + 1))         ;;
    esac

    echo "[${severity}] ${message}: ${session_file}"
}

# ---------------------------------------------------------------------------
# IOC checks
# ---------------------------------------------------------------------------

# IOC 0: token_denied counter alongside cp_security_token, in a session
# whose origin is badpass or otherwise non-benign.
#
# - token_denied is incremented by do_token_denied() (cpsrvd.pl:3821)
#   every time a request supplies the wrong cp_security_token. The
#   session is killed on the third failure.
# - cp_security_token itself is set by newsession() unconditionally
#   while security tokens are enabled (Cpanel/Server.pm:2290), so its
#   presence is NOT by itself an IOC. The pair (token_denied,
#   cp_security_token) tells us only that someone is actively trying
#   tokens against this session.
#
# Auth markers (successful_*_auth_with_timestamp, hasroot=1,
# tfa_verified=1, or an access_log hit on the security token) cannot
# legitimately appear in a badpass session: the badpass call site
# (Cpanel/Server.pm:1244-1252) doesn't pass them, hasroot is not even
# in _SESSION_PARTS (Cpanel/Server.pm:2216-2247), and tfa_verified is
# forced to 0 unless the caller passes a truthy value (line 2295).
#
# Severity tiers:
#   CRITICAL - badpass origin AND auth markers present (post-exploit)
#   INFO     - badpass origin, no auth markers, pass looks like a real
#              encoded password (likely an unrelated failed login that
#              happened to receive bad-token traffic)
#   WARNING  - origin is neither badpass nor a known-benign method
#              (handle_form_login, create_user_session,
#              handle_auth_transfer); the suspicious origin itself is
#              the IOC
#
# Legitimate badpass sessions never carry a pass= line (the badpass
# call site at Cpanel/Server.pm:1244-1252 does not pass `pass` to
# newsession, and saveSession only writes pass= when length is
# non-zero - Cpanel/Session.pm:181). When we see one anyway we defer
# classification to IOC 5 (check_failed_exploit_attempt), which flags
# it as ATTEMPT.
check_token_denied_with_injected_token() {
    local session_file="$1"

    grep -q '^token_denied='      "$session_file" || return
    grep -q '^cp_security_token=' "$session_file" || return

    local token_val external_auth internal_auth hasroot tfa used
    token_val=$(get_field      "$session_file" cp_security_token)
    external_auth=$(get_field  "$session_file" successful_external_auth_with_timestamp)
    internal_auth=$(get_field  "$session_file" successful_internal_auth_with_timestamp)
    hasroot=$(get_field        "$session_file" hasroot)
    tfa=$(get_field            "$session_file" tfa_verified)
    used=""
    if [ -r "$ACCESS_LOG" ]; then
        used=$(grep -aF -- "$token_val" "$ACCESS_LOG" | grep -m1 " 200 ")
    fi

    local has_auth_markers=0
    if [ -n "$external_auth" ] || [ -n "$internal_auth" ] \
       || [ "$hasroot" = "1" ] || [ "$tfa" = "1" ] || [ -n "$used" ]; then
        has_auth_markers=1
    fi

    if grep -q '^origin_as_string=.*method=badpass' "$session_file"; then
        if [ "$has_auth_markers" -eq 1 ]; then
            report_finding CRITICAL "$session_file" "$token_val" \
                "Exploitation artifact - token_denied with injected cp_security_token (badpass origin, token used)"
        else
            # A pass= line on a badpass session is itself anomalous;
            # defer to IOC 5 (ATTEMPT).
            if grep -q '^pass=' "$session_file"; then
                return
            fi
            report_finding INFO "$session_file" "$token_val" \
                "Possible injected session (badpass origin, no usage observed)"
        fi
    elif grep -q '^origin_as_string=.*method=handle_form_login' "$session_file" || \
         grep -q '^origin_as_string=.*method=create_user_session' "$session_file" || \
         grep -q '^origin_as_string=.*method=handle_auth_transfer' "$session_file"; then
        # Known-benign origins where token_denied + cp_security_token
        # genuinely happens during normal use.
        return
    else
        report_finding WARNING "$session_file" "$token_val" \
            "Suspicious session with token_denied + cp_security_token (non-badpass origin)"
    fi
}

# IOC 1: A session that still has its pre-auth marker file but already
# contains an auth-success timestamp (external or internal).
#
# write_session creates $SESSIONS_DIR/preauth/<session_name> when the
# session is written with needs_auth=1, and removes that marker once
# needs_auth is cleared on promotion (Cpanel/Session.pm:225-235). A
# legitimately authenticated session therefore never has both the
# preauth marker and an auth-success timestamp at the same time.
#
# Both successful_external_auth_with_timestamp and
# successful_internal_auth_with_timestamp are checked: the original
# poc.py payload injects the external variant; the watchtowr payload
# (poc/poc_watchtowr.py:35) injects the internal variant.
check_preauth_with_auth_attrs() {
    local session_file="$1"
    local session_name preauth_file
    session_name=$(basename "$session_file")
    preauth_file="$SESSIONS_DIR/preauth/$session_name"

    [ -f "$preauth_file" ] || return

    local marker
    if grep -qE '^successful_external_auth_with_timestamp=' "$session_file"; then
        marker="successful_external_auth_with_timestamp"
    elif grep -qE '^successful_internal_auth_with_timestamp=' "$session_file"; then
        marker="successful_internal_auth_with_timestamp"
    else
        return
    fi

    report_finding CRITICAL "$session_file" \
        "$(get_field "$session_file" cp_security_token)" \
        "Injected session - ${marker} present in pre-auth session"
}

# IOC 2: tfa_verified=1 outside of a legitimate origin method.
#
# tfa_verified=1 is set in only two places:
#   - Cpanel/Security/Authn/TwoFactorAuth/Verify.pm:122, after a real
#     TFA token validation succeeds.
#   - Cpanel/Server.pm:2295, when a caller passes tfa_verified=1 to
#     newsession().
# In both cases the legitimate origin method is one of handle_form_login,
# create_user_session, or handle_auth_transfer. tfa_verified=1 with any
# other origin (notably badpass) cannot occur in a benign flow.
check_tfa_with_bad_origin() {
    local session_file="$1"

    grep -qE '^tfa_verified=1$' "$session_file" || return
    grep -q '^origin_as_string=.*method=handle_form_login'    "$session_file" && return
    grep -q '^origin_as_string=.*method=create_user_session'  "$session_file" && return
    grep -q '^origin_as_string=.*method=handle_auth_transfer' "$session_file" && return

    report_finding WARNING "$session_file" \
        "$(get_field "$session_file" cp_security_token)" \
        "Session with tfa_verified=1 but suspicious origin"
}

# IOC 3: Session file contains a line that is not in `key=value` form.
#
# Three structural invariants together guarantee that every legitimate
# line matches ^[A-Za-z_][A-Za-z0-9_]*=:
#
#   1. write_session serializes via Cpanel::Config::FlushConfig::flushConfig
#      with '=' as the separator (Cpanel/Session.pm:221), so the on-disk
#      format is one key=value pair per line.
#   2. Keys come from a fixed whitelist (_SESSION_PARTS at
#      Cpanel/Server.pm:2216-2247, applied at lines 2268-2270), so they
#      always match the identifier shape above.
#   3. Cpanel::Session::filter_sessiondata strips \r\n from every value
#      (Cpanel/Session.pm:315) and additionally strips \r\n=, from origin
#      sub-values (line 312), so values can never re-introduce line
#      breaks. The `pass` value is additionally encoded by saveSession
#      (Cpanel/Session.pm:181-189) into either lowercase hex (with-secret
#      via Cpanel::Session::Encoder->encode_data) or the literal prefix
#      `no-ob:` followed by lowercase hex (no-secret via
#      Cpanel::Session::Encoder->hex_encode_only), so it cannot
#      reintroduce structural characters either.
#
# Any non-blank line that fails the regex is the footprint of an
# injection that bypassed these invariants - typically raw payload bytes
# that didn't form valid key=value pairs. Note: an injection whose
# smuggled lines DO match key=value (e.g. the watchtowr payload at
# poc/poc_watchtowr.py:35, which fabricates successful_internal_auth_
# with_timestamp/user/tfa_verified/hasroot lines) will not trip this
# check; it is caught by IOC-0 and IOC-4 instead.
check_malformed_session_line() {
    local session_file="$1"

    # Look for any non-blank line that doesn't start with key=...
    grep -nE -v '^[A-Za-z_][A-Za-z0-9_]*=|^[[:space:]]*$' "$session_file" >/dev/null 2>&1 || return

    report_finding CRITICAL "$session_file" \
        "$(get_field "$session_file" cp_security_token)" \
        "Malformed session line(s) detected (not key=value - newline injection footprint)"
}

# IOC 4: badpass origin combined with markers that no legitimate cpsrvd
# code path writes into a badpass session.
#
# The badpass call site (Cpanel/Server.pm:1244-1252) is:
#
#   $randsession = $self->newsession(
#       'needs_auth' => 1,
#       %security_token_options,            # adds cp_security_token
#       'origin' => { 'method' => 'badpass' },
#   );
#
# %security_token_options is why badpass sessions legitimately carry
# cp_security_token, but no auth-related options are ever supplied.
# newsession() filters %OPTS through the _SESSION_PARTS whitelist
# (Cpanel/Server.pm:2216-2247, applied at lines 2268-2270), so any key
# not in that whitelist cannot land in the session via newsession at
# all. Per marker:
#
#   successful_external_auth_with_timestamp - whitelisted, but the
#       badpass caller doesn't pass it
#   successful_internal_auth_with_timestamp - same
#   tfa_verified=1 - newsession unconditionally writes 0 unless the
#       caller passed a truthy value (Cpanel/Server.pm:2295), and the
#       badpass caller doesn't
#   hasroot=1 - NOT in _SESSION_PARTS, so newsession cannot write it
#       for ANY session. A repo-wide grep finds no caller of
#       Cpanel::Session::Modify->set('hasroot', ...) either: hasroot is
#       never written to a session by legitimate code. Its presence in
#       any session file is conclusive evidence of newline injection
#       (the watchtowr payload at poc/poc_watchtowr.py:35 smuggles
#       hasroot=1 via \r\n in a user-controlled field).
check_badpass_with_auth_markers() {
    local session_file="$1"

    grep -q '^origin_as_string=.*method=badpass' "$session_file" || return

    local markers=()
    grep -q '^successful_external_auth_with_timestamp=' "$session_file" \
        && markers+=("successful_external_auth_with_timestamp")
    grep -q '^successful_internal_auth_with_timestamp=' "$session_file" \
        && markers+=("successful_internal_auth_with_timestamp")
    grep -qE '^hasroot=1$'      "$session_file" && markers+=("hasroot=1")
    grep -qE '^tfa_verified=1$' "$session_file" && markers+=("tfa_verified=1")

    [ "${#markers[@]}" -gt 0 ] || return

    local joined
    joined=$(IFS=,; echo "${markers[*]}")
    report_finding CRITICAL "$session_file" \
        "$(get_field "$session_file" cp_security_token)" \
        "badpass origin combined with authenticated markers ($joined) - impossible in benign flow"
}

# IOC 5: Failed exploit attempt - a badpass session that carries a
# pass= line, a token_denied counter, and no auth markers.
#
# A legitimate badpass session is created at Cpanel/Server.pm:1244-1252:
#
#   $randsession = $self->newsession(
#       'needs_auth' => 1,
#       %security_token_options,
#       'origin' => { 'method' => 'badpass' },
#   );
#
# %security_token_options carries only cp_security_token,
# requested_token_at_next_login, and previous_session_user
# (Cpanel/Server.pm:1205-1226) - never `pass`. saveSession only
# writes a pass= line when length($session_ref->{pass}) is non-zero
# (Cpanel/Session.pm:181), so legitimate badpass sessions have no
# pass= line at all.
#
# An exploit that tampers with a user-controlled field on a
# badpass-bound request leaves a pass= line behind (saveSession
# encodes it as `<hex>` or `no-ob:<hex>` per Cpanel/Session.pm:181-189,
# but the format is irrelevant - its presence is the indicator). Combined
# with token_denied (someone was poking at cp_security_token) and the
# absence of auth markers (the injection didn't promote - otherwise
# IOC-0 or IOC-4 fires CRITICAL), this is the signature of a failed
# exploit attempt.
check_failed_exploit_attempt() {
    local session_file="$1"

    grep -q '^origin_as_string=.*method=badpass' "$session_file" || return
    grep -q '^token_denied=' "$session_file" || return

    # If auth markers are present, IOC-4 (CRITICAL) handles it.
    grep -q '^successful_internal_auth_with_timestamp=' "$session_file" && return
    grep -q '^successful_external_auth_with_timestamp=' "$session_file" && return

    # Legitimate badpass sessions never carry pass=.
    grep -q '^pass=' "$session_file" || return

    report_finding ATTEMPT "$session_file" "$(get_field "$session_file" cp_security_token)" \
        "Failed exploit attempt (badpass origin, token_denied, no auth markers, anomalous pass= line)"
}

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

scan_sessions() {
    local session_file
    while IFS= read -r -d '' session_file; do
        check_token_denied_with_injected_token "$session_file"
        check_preauth_with_auth_attrs          "$session_file"
        check_tfa_with_bad_origin              "$session_file"
        check_malformed_session_line           "$session_file"
        check_badpass_with_auth_markers        "$session_file"
        check_failed_exploit_attempt           "$session_file"
    done < <(find "$SESSIONS_DIR/raw" -type f -print0 2>/dev/null)
}


print_summary() {
    local total=$((COUNT_CRITICAL + COUNT_WARNING + COUNT_INFO + COUNT_ATTEMPT))

    echo
    echo "================================================================="
    echo "                       SCAN SUMMARY"
    echo "================================================================="
    echo "  CRITICAL findings: $COUNT_CRITICAL"
    echo "  WARNING  findings: $COUNT_WARNING"
    echo "  ATTEMPT  findings: $COUNT_ATTEMPT"
    echo "  INFO     findings: $COUNT_INFO"
    echo "  Total            : $total"
    echo "-----------------------------------------------------------------"

    if [ "$total" -eq 0 ]; then
        echo "[+] No indicators of compromise found."
        return
    fi

    # --purge has destructive blast radius (live session files for every
    # logged-in user). Require either --yes for non-interactive use, or
    # an explicit "yes" at an attached TTY.
    if [ "$PURGE" -eq 1 ] && [ "$ASSUME_YES" -ne 1 ]; then
        if [ ! -t 0 ]; then
            echo "[ERROR] --purge requires --yes when stdin is not a TTY (cron, pipes, etc)" >&2
            echo "        Re-run with --yes to confirm deletion." >&2
            exit 64
        fi
        echo
        echo "About to delete ${#FINDING_SESSIONS[@]} session file(s) plus matching preauth markers."
        local confirm=""
        read -r -p "Type 'yes' to confirm: " confirm
        if [ "$confirm" != "yes" ]; then
            echo "[+] Aborted; no files deleted."
            PURGE=0
        fi
    fi


    # For each unique session, print only the highest-severity finding, then dump/purge as needed.
    local i session token severity message found=0
    for i in "${!FINDING_SESSIONS[@]}"; do
        session="${FINDING_SESSIONS[$i]}"
        token="${FINDING_TOKENS[$i]}"
        severity="${FINDING_SEVERITIES[$i]}"
        found=0
        # Find the first matching finding for this session and severity.
        # Use `read` with three names so the last variable (entry_msg)
        # absorbs any remaining `|` characters - the previous `${var##*|}`
        # form took only the suffix after the LAST `|`, which would
        # silently truncate any future message that contained one.
        for entry in "${FINDINGS[@]}"; do
            local entry_sev entry_file entry_msg
            IFS='|' read -r entry_sev entry_file entry_msg <<< "$entry"
            if [ "$entry_file" = "$session" ] && [ "$entry_sev" = "$severity" ]; then
                message="$entry_msg"
                found=1
                break
            fi
        done
        echo
        echo "================================================================="
        echo "  SESSION: $session"
        echo "================================================================="
        echo "  Findings:"
        if [ "$found" -eq 1 ]; then
            printf "    [%-8s] %s\n" "$severity" "$message"
        else
            printf "    [%-8s] %s\n" "$severity" "(no message found)"
        fi
        echo
        if [ "$VERBOSE" -eq 1 ]; then
            dump_session "$session" "$token"
        fi
        if [ "$PURGE" -eq 1 ]; then
            echo "    [ACTION] Deleting session file: $session"
            rm -f -- "$session"
            local preauth_marker="$SESSIONS_DIR/preauth/$(basename "$session")"
            if [ -e "$preauth_marker" ]; then
                echo "    [ACTION] Deleting preauth marker: $preauth_marker"
                rm -f -- "$preauth_marker"
            fi
        fi
    done

    if [ "$COUNT_CRITICAL" -gt 0 ] || [ "$COUNT_WARNING" -gt 0 ]; then
        echo
        echo "[!] INDICATORS OF COMPROMISE DETECTED - IMMEDIATE ACTION REQUIRED"
        echo "    1. Purge all affected sessions"
        echo "    2. Force password reset for root and all WHM users"
        echo "    3. Audit /var/log/wtmp and WHM access logs for unauthorized access"
        echo "    4. Check for persistence mechanisms (cron, SSH keys, backdoors)"
    fi
}

if [ ! -d "$SESSIONS_DIR/raw" ]; then
    echo "[ERROR] Sessions directory not found: $SESSIONS_DIR/raw" >&2
    echo "        Pass --sessions-dir DIR to point at a different location" >&2
    echo "        (the default is /var/cpanel/sessions)." >&2
    exit 64
fi

echo "[*] Scanning session files for injection indicators..."
scan_sessions
print_summary

# Exit codes (for cron / monitoring):
#   2 - at least one CRITICAL or WARNING finding (compromise indicators)
#   1 - only ATTEMPT or INFO findings (probing, no confirmed compromise)
#   0 - clean scan
if [ "$COUNT_CRITICAL" -gt 0 ] || [ "$COUNT_WARNING" -gt 0 ]; then
    exit 2
elif [ "$COUNT_ATTEMPT" -gt 0 ] || [ "$COUNT_INFO" -gt 0 ]; then
    exit 1
fi
exit 0

There is a scan summary section that shows

Example output:

=================================================================
                       SCAN SUMMARY
=================================================================
  CRITICAL findings: 1
  WARNING  findings: 0
  ATTEMPT  findings: 1
  INFO     findings: 0
  Total            : 2
-----------------------------------------------------------------
=================================================================
  SESSION: /var/cpanel/sessions/raw/:cusK9ghEd6MPo4eW
=================================================================
  Findings:
    [ATTEMPT ] Failed exploit attempt (badpass origin, token_denied, no auth markers, anomalous pass= line)
    
=================================================================
  SESSION: /var/cpanel/sessions/raw/:TMnjH0tBK6jP2V3I
=================================================================
  Findings:
    [CRITICAL] Exploitation artifact - token_denied with injected cp_security_token (badpass origin, token used)

[!] INDICATORS OF COMPROMISE DETECTED - IMMEDIATE ACTION REQUIRED
    1. Purge all affected sessions
    2. Force password reset for root and all WHM users
    3. Audit /var/log/wtmp and WHM access logs for unauthorized access
    4. Check for persistence mechanisms (cron, SSH keys, backdoors)

Some of the results may be false positives, which means you may have to manually check and see if results are valid or not.

cPanel overhauled the detection script and should be accurate now.

ℹ️ It appears that there can be a limit to the total number of sessions available on a system. You may want to double check how old the session files are (ls -lt /var/cpanel/sessions/raw) to ensure you catch all login attempts. It is theoretically possible that the system was compromised, but the session that did it is no longer available, meaning it would not show up in the script provided by cPanel. You should still be able to check the access_logs.

Checking the access logs

This may not be the most fool proof way to check for a compromise, but it may help identify if an IP address has been authenticated and accessed restricted endpoints.

Replace valid-ip-address1 and valid-ip-address2 with your IP addresses.

grep "listacct\|terminal\|json-api" /usr/local/cpanel/logs/access_log |  grep -v "403\|401" | grep -v "valid-ip-address1\|valid-ip-address2"

Basically, we are searching for any valid requests that contain listacct, terminal, or json-api.

How to check the last time WHM was upgraded

If your server is set to automatically update WHM, it may be beneficial to know when it last updated. You can check the update logs in /var/cpanel/updatelogs to check the time and version.

As a shortcut, you can use the following command to group all of the version changes from all of the update log files.

head /var/cpanel/updatelogs/update.*.log -n 20 | grep version | sort

Example output:

[2026-04-29 23:12:04 -0000]   Running version '11.134.0.19' of updatenow.
[2026-04-29 23:12:04 -0000]   Become an updatenow.static for version: 11.134.0.20
[2026-04-29 23:12:04 -0000]   Detected version '11.134.0.19' from version file.
[2026-04-29 23:12:04 -0000]   Switching to version 11.134.0.20 of updatenow to determine if we can reach that version without failure.
[2026-04-29 23:12:04 -0000]   Target version set to '11.134.0.20'
[2026-04-30 23:12:04 -0000]   Detected version '11.134.0.20' from version file.
[2026-04-30 23:12:04 -0000]   Running version '11.134.0.20' of updatenow.
[2026-04-30 23:12:04 -0000]   Target version set to '11.134.0.20'

Links:

https://labs.watchtowr.com/the-internet-is-falling-down-falling-down-falling-down-cpanel-whm-authentication-bypass-cve-2026-41940

https://github.com/watchtowrlabs/watchTowr-vs-cPanel-WHM-AuthBypass-to-RCE.py

https://hadrian.io/blog/cve-2026-41940-a-critical-authentication-bypass-in-cpanel

Enable port mirroring on Mikrotik CRS 3xx

First we need to setup the the Target port, i.e., the port we want to send our mirrored traffic to. Go to Switch -> Settings -> Select the Switch -> Mirror Target. Select the port you want to mirror to.

Next, we need to configure which port(s) we want to use as source ports.

Go to Switch -> Ports -> Select the Port

Select Mirror Ingress and/or Mirror Egress and apply.

That is it. All traffic on your configured ports will now mirror to the target port.

Downloading files from Ubiquiti radio (sh: /usr/libexec/sftp-server: not found)

SFTP and rsync do not work on Ubiquiti radios. When you attempt to SFTP, you receive the error:

sh: /usr/libexec/sftp-server: not found

We can however use SCP with the -O option, which tells SCP to use the legacy SCP protocol, for file transfer instead of SFTP. The following command will download the radio config.

scp -O ubnt@192.168.1.20:/tmp/system.cfg ./

If you want to download an entire directory, or the entire OS for that matter, you can use the -r flag for SCP. The following command will download all the files in the /tmp directory.

scp -O -r ubnt@192.168.1.20:/tmp ./

Bad server host key: Invalid key length

You may encounter the following error when SSHing to legacy systems.

Bad server host key: Invalid key length

This happens due to older devices not using a larger key size.

A work around is to add an exception in your SSH config file allowing a smaller key size for specific hosts.

You can do this by adding the following to your ~/.ssh/config file. Change the IP addresses to the hosts you are trying to connect to. You can add more IPs if needed. Just ensure there is a space between them.

Host 192.168.1.20 192.168.1.1
     RSAMinSize 1024

How to receive an Implicit Intent in an Android App

The goal is to be able to display text in our Main Activity from an implicit intent via the share feature in Android.

Steps:

  1. Modify the Android Manifest to receive an implicit intent.
  2. Setup Main Activity to display received text.

These steps assume you have at least a basic project set up in Android Studio.

Helpful links:

https://developer.android.com/guide/components/intents-filters

Modify the Android Manifest to receive an implicit intent

We will need to add the following to the <intent-filter> section of our Main Activity.

<action android:name="android.intent.action.SEND"
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain"/>

A helpful note from the page Android Developer page:

Note: To receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they declared the CATEGORY_DEFAULT category. If you do not declare this category in your intent filter, no implicit intents will resolve to your activity.

This means by default, we can not receive an implicit intent to the MainActivity in an Android app, unless we add the DEFAULT category.

Our app should now show up in the Android Share menu when you select some text and hit “Share”.

Setup Main Activity to display received text

Now that we can send text to our app, we should do something with it.

In our Main Activity we have a Text View that we will update. Change myTextView to your Text View id.

val myText: TextView = findViewById(R.id.myTextView)
myText.text = intent.getStringExtra(Intent.EXTRA_TEXT)

Now if we share some text and send it to our app, it updates the Text View with our selected text.

Ansible Playbook for Ubuntu UFW Firewall Rules

Here is a simple Ansible UFW firewall playbook.

You will need to install the Ansible collection community.general if it is not already installed.

ansible-galaxy collection install community.general

Next create the playbook. Modify the ports to your liking. Also remember you can put these variables in the Ansible inventory file so each hosts can have different settings.

---
- hosts: ubuntu
  become: true
  vars:
    ssh_port: 22
    http_port: 80
    https_port: 443

  tasks:
  - name: Ensure UFW is installed
    apt:
      name: ufw
      state: present
      update_cache: yes

  - name: Restrict SSH access to local IP addresses (RFC 1918)
    block:
      - name: Allow SSH from 10.0.0.0/8
        community.general.ufw:
          rule: allow
          from_ip: 10.0.0.0/8
          port: "{{ ssh_port }}"
          proto: tcp
      - name: Allow SSH from 172.16.0.0/12
        community.general.ufw:
          rule: allow
          from_ip: 172.16.0.0/12
          port: "{{ ssh_port }}"
          proto: tcp
      - name: Allow SSH from 192.168.0.0/16
        community.general.ufw:
          rule: allow
          from_ip: 192.168.0.0/16
          port: "{{ ssh_port }}"
          proto: tcp

  - name: Allow HTTPS access from the world
    community.general.ufw:
      rule: allow
      port: "{{ https_port }}"
      proto: tcp

  - name: Allow HTTP access from the world
    community.general.ufw:
      rule: allow
      port: "{{ http_port }}"
      proto: tcp

  - name: Enable UFW and set default policy to deny incoming
    community.general.ufw:
      state: enabled
      policy: deny

Save the playbook as ubuntu_firewall.yaml

Run the playbook with:

ansible-playbook ubuntu_firewall.yaml -i inventory/hosts

Here is a more advanced playbook that will loop through multiple IP addresses and ports.

---
- hosts: ubuntu
  become: true
  vars:
    local_ports:
      - { port: '22', proto: 'tcp' }  # SSH
      - { port: '161', proto: 'udp' }  # SNMP
    public_ports:
      - { port: '80', proto: 'tcp' }  # HTTP
      - { port: '443', proto: 'tcp' } # HTTPS
    local_ips:
      - 10.0.0.0/8
      - 172.16.0.0/12
      - 192.168.0.0/16

  tasks:
    - name: Ensure UFW is installed
      apt:
        name: ufw
        state: present
        update_cache: yes

    - name: Allow public_ports
      community.general.ufw:
        rule: allow
        port: "{{ item.port }}"
        proto: "{{ item.proto }}"
      loop: "{{ public_ports }}"


    - name: Allow access to local_ports from RFC 1918 local addresses
      block:
        - name: Allow local_ports from RFC 1918 local IPs
          community.general.ufw:
            rule: allow
            from_ip: "{{ item.0 }} "
            port: "{{ item.1.port }}"
            proto: "{{ item.1.proto }}"
          loop: "{{ local_ips | product(local_ports) | list }}"

    - name: Enable UFW and set default policy to deny incoming
      community.general.ufw:
        state: enabled
        policy: deny

How to flash unsigned firmware on a Ubiquiti Airmax Radio

Here are some notes on downgrading a Ubiquiti Airmax radio so it can run unsigned firmware.

Disclaimer, the following steps are potentially dangerous. Proceed with caution.

Ubiquiti introduced signed firmware around version 5.12. After that, you couldn’t flash unsigned firmware if a device already had signed firmware. You also couldn’t downgrade below 5.12.

Ubiquiti uses the update utility to enforce only flashing signed firmware. So what happens if you swap out the update utility with one from an unsigned firmware version?

This is the hack we’ll explore.

Here is a quick overview.

  1. Download firmware.
  2. Extract ubntbox out of the unsigned firmware.
  3. Move files (ubntbox, and unsigned firmware) to target radio.
  4. Modify libevent versions in ubntbox to match the current signed firmware. Should only be needed if firmware version number is different.
  5. Upgrade! “Downgrade”…

Downloading firmware

You can download unsigned firmware from Ubiquiti. https://ui.com/download

Here is a link for the PowerBeam firmware. https://ui.com/download/software/nbe-m5-400

ℹ️Pro tip, you should be able to wget the firmware directly to a radio with wget http://dl.ubnt.com/firmwares/XW-fw/v5.6.15/XW.v5.6.15-sign.31612.170908.1440.bin
Note the http. No https. The wget version in older firmware has issues with SSL/TLS.

Extract ubntbox from the Unsigned Firmware

For this step we need binwalk.

sudo apt install binwalk

Next, extract the firmware with binwalk.

binwalk -e ./XW.v5.6.3.bin

It will extract the firmware to a folder named _XW.v5.6.3.28591.151130.1735.bin.extracted

We want the ubntbox binary which is at the following location.

_XW.v5.6.3.28591.151130.1735.bin.extracted/squashfs-root/bin/ubntbox

Move files (ubntbox, and unsigned firmware) to target radio

ℹ️scp and sftp most likely will not work. To get around this, you can set up a local web server like apache to serve the files, move the files into the /var/www/html directory and download to the radio with wget. You may not be able to download executable files. You can work around this by running chmod 644 ubntbox, download with wget, then chmod +x ubntbox to make it executable again.

On our computer, install and start the apache webserver

sudo apt install apache2
sudo systemctl start apache2

Next, copy ubntbox and firmware files to /var/www/html/. Replace the firmware name if different.

cp ./ubntbox /var/www/html/
cp ./XW.v5.6.3.bin /var/www/html/

On the radio, cd to the /tmp directory. Download ubntbox and the firmware from your computer. Change the IP address to your webserver IP.

wget http://192.168.1.2/ubntbox
wget http://192.168.1.2/XW.v5.6.3.bin

Rename firmware to fwupdate.bin

mv XW.v5.6.3.bin fwupdate.bin

Ensure ubntbox is executable.

chmod +x ubntbox

Upgrade “Downgrade” radio

We are ready to update the radio.

./ubntbox fwupdate.real -m

You may encounter the following error.

./ubntbox: can't load library 'libevent_core-2.0.so.5'

Since ubntbox is a dynamically linked binary, we may need to change the libevent library references to match the libevent libraries on the system. You can find the current libevent libraries with find / | grep libevent

Example output.

XW.v5.6.15-sign.31612.170908.1440# find / | grep libevent
/lib/libevent-2.1.so.6
/lib/libevent-2.1.so.6.0.2
/lib/libevent_core-2.1.so.6
/lib/libevent_core-2.1.so.6.0.2
/lib/libevent_extra-2.1.so.6
/lib/libevent_extra-2.1.so.6.0.2
/lib/libevent_openssl-2.1.so.6
/lib/libevent_openssl-2.1.so.6.0.2

Replace all libevent references in ubntbox with the correct versions on the current firmware.

You should now be able to downgrade to an unsigned firmware version.

A few interesting notes.

  • /sbin is a link to /bin
  • fwupdate is a simlink to fwupdate.real which is a link to ubntbox.  
  • ubntbox is like Busybox
  • To download files, you may need to use wget over non https.

Ansible “PlayContext” error for RouterOS Community Collection

The following error is due to PlayContext being removed from ansible-core.

https://github.com/ansible-collections/ansible.netcommon/issues/541

"msg": "'PlayContext' object has no attribute 'verbosity'"

This can be fixed by updating the Ansible Collection.

You can list your current collections with

ansible-galaxy collection list

You may have multiple duplicates for different versions of Python and for local and system paths. I.e., /usr/lib/python3 and ~/.local/lib/python3

We can upgrade the collection with the following command.

ansible-galaxy collection install community.routeros --upgrade

How to “Lock” docker version on RHEL / RockyLinux / AlmaLinux

Sometimes it can be helpful to have a specific docker version that doesn’t change with a dnf update. To manually set the docker version, do the following.

Install dnf versionlock

dnf install 'dnf-command(versionlock)'

Next, lock the version for Docker and the Docker CLI.

dnf versionlock add docker-ce-3:27.5.0 docker-ce-cli-1:27.5.0

If you need to downgrade docker, you can do that with the following.

dnf downgrade docker-ce-3:27.5.0 docker-ce-cli-1:27.5.0

That should be it. If you want to check and see what packages are locked, run

dnf versionlock list

Example output:

Last metadata expiration check: 0:01:39 ago on Tue 08 Apr 2025 01:01:10 AM UTC.
docker-ce-3:27.5.0-1.el9.*
docker-ce-cli-1:27.5.0-1.el9.*

Changing Ubiquiti Radio password from Command Line

Most configuration changes to Ubiquiti radios can be done on the command line by modifing them in /tmp/system.cfg and then applying the configuration. The device password is a little more complicated. The password is in the system.cfg config file, but it is hashed. To change the password, we must change the password via ssh, then update the config password hash to match the hash in /etc/passwd.

We’ll cover two ways to update the password for a Ubiquiti radio. The first method uses the UBNTMOD script. The second shows a more hands on approach.

Method 1: Using the UBNTMOD script.

Download the UBNTMOD script and make it executable.

wget http://incredigeek.com/home/downloads/ubntmod/ubntmod.sh
chmod u+x ubntmod.sh
./ubntmod.sh -y 'ubnt,ubnt' -p 'newpassword' -i 192.168.1.20 -z

-y is the current username and password pair
-p is the new password
-i is the radio IP
-z saves the changes without rebooting.

Method 2: Changing password over SSH

To change the password we need to:

  • SSH to the radio
  • Change the current password with passwd
  • Copy the hash from /etc/passwd to /tmp/system.cfg
  • Save changes with /usr/etc/rc.d/rc.softrestart save

SSH into radio

ssh ubnt@192.168.1.20

Change the Password with passwd

passwd is the default utility to change the password for a user. Simply run passwd and follow the prompts

Example:

XW.v6.1.12# passwd
Changing password for ubnt
New password: <-- Enter password here
Retype password: <-- Reenter password here
Password for ubnt changed by ubnt
XW.v6.1.12# 

ℹ️Once you change the password with passwd, the password will change, but it wont be permanently saved until we copy the hash and then apply the change.

Copy Password hash to system.cfg

We can get the new password hash with

cat /etc/passwd

Example output:

admin:$1$QESek5FH$FUPpzbPbAvf0NUbYyJMj21:0:0:Administrator:/etc/persistent:/bin/sh

The section between the first and second colon, i.e., the two dots, “:”, is our hashed password. This is what we need to copy into the system.cfg config.

Edit the config file

vi /tmp/system.cfg

Find the line that starts with users.1.password= and replace everything after the equals sign with our new hash. For example:

users.1.password=$1$QESek5FH$FUPpzbPbAvf0NUbYyJMj21

ℹ️VI can be a little tricky to deal with, you can hit i, to enter insert mode, delete everything after the =, and then right click with your mouse to paste in the password hash.

Apply the new Password Permanently

Save the changes with /usr/etc/rc.d/rc.softrestart save command.

XW.v6.1.12# /usr/etc/rc.d/rc.softrestart save 
--- /tmp/.running.cfg.919
+++ /tmp/.system.cfg.919
@@ -81,7 +81,7 @@
system.cfg.version=65546
system.eirp.status=disabled
users.1.name=ubnt
-users.1.password=$1$5FJMj2H$FbkP6UAb8yvfES0NUbPpzbQ <- Old Password Hash
+users.1.password=$1$QESek5FH$FUPpzbPbAvf0NUbYyJMj21 <- New Password Hash
users.1.status=enabled
users.status=enabled
wireless.1.addmtikie=enabled
Fast users script build Success.
Fixup Startup_list …Done.
XW.v6.1.12#

ℹ️Your existing ssh connection should stay connected which can be handy if something did not work correctly. Launch another terminal, or log in the web interface, to verify that the new password works.