#!/bin/sh
# php2shell-check.sh: "Am I patched?" for PHP2Shell (CVE-2026-109618 and CVE-2026-109619).
# Burnt & Toast Journal. Run it on your OWN server:
#
#     sh php2shell-check.sh
#
# What it does:  runs the PHP programs it can find on this machine with -v (and the command-line
#                PHP with -r to read three settings, four on PHP 8.5), then compares their versions with the
#                fixed releases from the PHP project's advisory of 21 October 2026.
# What it never does:  it sends nothing over the network, changes no files or settings,
#                and needs no root (run it as your normal user). It only reads.
#
# Results:  Patched / Needs updating / Can't tell, ask your host
# Exit code: 0 patched, 1 needs updating, 2 can't tell, 3 no PHP found.
#
# Fixed releases (https://www.php.net/archive/2026.php, 21 Oct 2026):
#     8.5.12, 8.4.27, 8.3.36, 8.2.35   (and 8.6.0RC4 for the 8.6 test releases)
# PHP 8.1 and older get no new releases from the PHP project.
#
# Not legal or security advice. If in doubt, ask your host.

CHECK_VERSION="2026-10-24"

# ---------------------------------------------------------------------------------------------
# The fixed release for each supported branch. Keep in step with the guide's table.
# ---------------------------------------------------------------------------------------------
fixed_patch_for_branch() {
	case "$1" in
		8.5) echo 12 ;;
		8.4) echo 27 ;;
		8.3) echo 36 ;;
		8.2) echo 35 ;;
		*) echo "" ;;
	esac
}

# classify_version VERSION [DISTRO]
#   VERSION  the PHP version string, e.g. 8.3.36 or 8.3.6-0ubuntu0.24.04.5 (PHP_VERSION or php -v)
#   DISTRO   "yes" if this PHP came from a Linux distribution or host package, else "no"
# Prints two lines: a result code (patched | update | canttell) and a short plain-English reason.
classify_version() {
	cv_ver=$1
	cv_distro=${2:-no}

	# The leading X.Y.Z, and whatever follows it.
	cv_core=$(printf '%s\n' "$cv_ver" | sed -n 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\).*$/\1.\2.\3/p')
	if [ -z "$cv_core" ]; then
		echo canttell
		echo "The version \"$cv_ver\" isn't in a format this check understands."
		return 0
	fi
	cv_rest=${cv_ver#"$cv_core"}
	cv_major=${cv_core%%.*}
	cv_minor=${cv_core#*.}; cv_minor=${cv_minor%%.*}
	cv_patch=${cv_core##*.}
	cv_branch="$cv_major.$cv_minor"

	# What kind of suffix is it?  "" (plain upstream), a PHP test release, -dev, or anything
	# else, which is a distribution or host build (-1ubuntu..., +deb..., .el9, remi, ~...).
	cv_kind=distro
	cv_pre=""
	case "$cv_rest" in
		"") cv_kind=plain ;;
		-dev|-DEV) cv_kind=dev ;;
		alpha[0-9]*|beta[0-9]*|RC[0-9]*|rc[0-9]*)
			cv_stage=${cv_rest%%[0-9]*}
			cv_n=${cv_rest#"$cv_stage"}
			case "$cv_n" in
				*[!0-9]*) ;;
				*) cv_kind=pre; cv_pre="$cv_stage $cv_n" ;;
			esac ;;
	esac

	if [ "$cv_kind" = dev ]; then
		echo canttell
		echo "This is a development build ($cv_ver), so its version number doesn't say which fixes it has."
		return 0
	fi

	# PHP 8.6 is only out as test releases. 8.6.0RC4 (21 Oct 2026) and later carry the fix.
	if [ "$cv_branch" = 8.6 ]; then
		if [ "$cv_kind" = pre ] && [ "$cv_patch" = 0 ]; then
			cv_stage=${cv_pre% *}; cv_n=${cv_pre#* }
			if { [ "$cv_stage" = RC ] || [ "$cv_stage" = rc ]; } && [ "$cv_n" -ge 4 ]; then
				echo patched
				echo "PHP $cv_ver is a test release that includes the fix (8.6.0RC4 or later). Test releases shouldn't run live websites."
			else
				echo update
				echo "PHP $cv_ver is an 8.6 test release from before the fix. 8.6.0RC4 or later has it, but a live website should use a supported release such as 8.5.12."
			fi
			return 0
		fi
		if [ "$cv_kind" = plain ]; then
			echo patched
			echo "PHP $cv_ver is newer than the 8.6.0RC4 test release, which already had the fix."
			return 0
		fi
		echo canttell
		echo "PHP $cv_ver is an 8.6 build this check can't place."
		return 0
	fi

	if [ "$cv_kind" = pre ]; then
		echo canttell
		echo "PHP $cv_ver is a test release this check can't place."
		return 0
	fi

	cv_fix=$(fixed_patch_for_branch "$cv_branch")

	if [ -n "$cv_fix" ]; then
		if [ "$cv_patch" -ge "$cv_fix" ]; then
			echo patched
			echo "PHP $cv_ver includes the fix, which arrived in $cv_branch.$cv_fix."
			return 0
		fi
		if [ "$cv_kind" = distro ] || [ "$cv_distro" = yes ]; then
			echo canttell
			echo "PHP $cv_ver is below $cv_branch.$cv_fix, but it's a build from your Linux distribution or host, which may have added the fix without changing the number (a \"backport\")."
			return 0
		fi
		echo update
		echo "PHP $cv_ver is below the fixed release $cv_branch.$cv_fix."
		return 0
	fi

	# Branches the PHP project no longer updates: 8.1 and older.
	if [ "$cv_major" -lt 8 ] || { [ "$cv_major" -eq 8 ] && [ "$cv_minor" -le 1 ]; }; then
		if [ "$cv_kind" = distro ] || [ "$cv_distro" = yes ]; then
			echo canttell
			echo "PHP $cv_branch no longer gets fixes from the PHP project. This is a distribution or host build, which may have a backported fix. Either way, plan a move to a supported version."
			return 0
		fi
		echo update
		echo "PHP $cv_branch no longer gets fixes from the PHP project. Move to a supported version (8.2.35 or later)."
		return 0
	fi

	echo canttell
	echo "PHP $cv_branch isn't a branch covered by the 21 October 2026 advisory."
	return 0
}

# ---------------------------------------------------------------------------------------------
# Everything below only READS this machine.
# ---------------------------------------------------------------------------------------------

# The version from "<binary> -v" output: the first "PHP x.y.z..." token.
version_from_v_output() {
	sed -n 's/.*PHP \([0-9][0-9]*\.[0-9][0-9]*\.[0-9][^ ,]*\).*/\1/p' | head -n 1
}

# True if NAME is a PHP program name: php, php-cgi, php-fpm, lsphp, frankenphp, or one of the
# first three followed by a version (php8, php83, php8.3, php-fpm8.3). Never phpize, php-config,
# phpunit, phpdbg or anything else that happens to start with "php".
php_name_ok() {
	pno_n=$1
	case "$pno_n" in php|php-cgi|php-fpm|lsphp|frankenphp) return 0 ;; esac
	pno_v=""
	for pno_pre in php-cgi php-fpm php; do
		case "$pno_n" in "$pno_pre"[0-9]*) pno_v=${pno_n#"$pno_pre"}; break ;; esac
	done
	[ -n "$pno_v" ] || return 1
	case "$pno_v" in *[!0-9.]*|*.*.*|*.) return 1 ;; esac
	return 0
}

# "yes" if the binary belongs to an installed package, or its -v output says "Built by ...".
is_distro_build() {
	idb_bin=$1
	idb_out=$2
	case "$idb_out" in *"Built by "*) echo yes; return 0 ;; esac
	case "$idb_bin" in
		/opt/remi/*|/opt/cpanel/ea-php*|/opt/alt/php*|/opt/plesk/php/*|/usr/local/lsws/*) echo yes; return 0 ;;
	esac
	if command -v dpkg >/dev/null 2>&1 && dpkg -S "$idb_bin" >/dev/null 2>&1; then echo yes; return 0; fi
	if command -v rpm >/dev/null 2>&1 && rpm -qf "$idb_bin" >/dev/null 2>&1; then echo yes; return 0; fi
	if command -v apk >/dev/null 2>&1 && apk info --who-owns "$idb_bin" >/dev/null 2>&1; then echo yes; return 0; fi
	echo no
}

# Candidate PHP programs: on PATH, and in the usual places packages and control panels put them.
list_candidates() {
	for n in php php-cgi php-fpm lsphp frankenphp; do
		command -v "$n" 2>/dev/null
	done
	for p in /usr/bin/php[0-9]* /usr/bin/php-cgi* /usr/sbin/php-fpm* /usr/local/bin/php /usr/local/bin/php[0-9]* /usr/local/bin/php-cgi* /usr/local/bin/php-fpm* /usr/local/sbin/php-fpm* \
		/opt/remi/php*/root/usr/bin/php /opt/remi/php*/root/usr/sbin/php-fpm \
		/opt/cpanel/ea-php*/root/usr/bin/php /opt/cpanel/ea-php*/root/usr/sbin/php-fpm \
		/opt/alt/php*/usr/bin/php /opt/alt/php*/usr/sbin/php-fpm \
		/opt/plesk/php/*/bin/php /opt/plesk/php/*/sbin/php-fpm \
		/usr/local/lsws/lsphp*/bin/lsphp /usr/local/lsws/lsphp*/bin/php \
		/usr/local/bin/frankenphp; do
		[ -f "$p" ] && [ -x "$p" ] && php_name_ok "$(basename "$p")" && printf '%s\n' "$p"
	done
}

# Resolve symlinks where we can, so the same program is only checked once.
real_path() {
	if command -v readlink >/dev/null 2>&1; then readlink -f "$1" 2>/dev/null || printf '%s\n' "$1"
	else printf '%s\n' "$1"; fi
}

label_for() {
	case "$(basename "$1")" in
		php-fpm*) echo "PHP-FPM (website)" ;;
		php-cgi*) echo "php-cgi (website)" ;;
		lsphp*) echo "LiteSpeed PHP (website)" ;;
		frankenphp*) echo "FrankenPHP (website)" ;;
		*) echo "Command-line PHP" ;;
	esac
}

say_result() {
	case "$1" in
		patched) echo "Patched" ;;
		update) echo "Needs updating" ;;
		*) echo "Can't tell, ask your host" ;;
	esac
}

main() {
	echo "PHP2Shell check (CVE-2026-109618, CVE-2026-109619), version $CHECK_VERSION"
	echo "Reads this machine only. Sends nothing anywhere and changes nothing."
	echo

	worst=""            # patched < canttell < update
	found=0
	web_found=0
	seen=" "
	cli_bin=""

	for cand in $(list_candidates | sort -u); do
		php_name_ok "$(basename "$cand")" || continue
		rp=$(real_path "$cand")
		case "$seen" in *" $rp "*) continue ;; esac
		seen="$seen$rp "

		case "$(basename "$rp")" in
			frankenphp*) out=$("$rp" version 2>/dev/null) ;;
			*) out=$("$rp" -v 2>/dev/null) ;;
		esac
		ver=$(printf '%s\n' "$out" | version_from_v_output)
		[ -z "$ver" ] && continue
		found=$((found + 1))

		label=$(label_for "$rp")
		case "$label" in *website*) web_found=1 ;; esac
		[ -z "$cli_bin" ] && [ "$label" = "Command-line PHP" ] && cli_bin=$rp

		distro=$(is_distro_build "$rp" "$out")
		res=$(classify_version "$ver" "$distro")
		code=$(printf '%s\n' "$res" | sed -n 1p)
		why=$(printf '%s\n' "$res" | sed -n 2p)

		echo "$label: $rp"
		echo "  Version: $ver"
		[ "$distro" = yes ] && echo "  Built by: your Linux distribution or host's packages"
		echo "  Result:  $(say_result "$code")"
		echo "  Why:     $why"
		echo

		case "$code" in
			update) worst=update ;;
			canttell) [ "$worst" != update ] && worst=canttell ;;
			patched) [ -z "$worst" ] && worst=patched ;;
		esac
	done

	# Apache with mod_php: the module is a library, not a program, so we can only say it's there.
	modphp=""
	for m in /usr/lib/apache2/modules/libphp*.so /usr/lib64/httpd/modules/libphp*.so /usr/lib/httpd/modules/libphp*.so \
		/etc/httpd/modules/libphp*.so /usr/local/apache/modules/libphp*.so /usr/local/apache2/modules/libphp*.so; do
		[ -f "$m" ] && modphp="$modphp $m"
	done
	if [ -n "$modphp" ]; then
		web_found=1
		echo "Apache mod_php is installed:$modphp"
		echo "  PHP's advisory rates the risk highest for mod_php. It normally matches the command-line"
		echo "  PHP's version from the same packages, but the upload check (php2shell-check.php) shows"
		echo "  the version your website actually runs."
		echo
	fi

	if [ "$found" -eq 0 ]; then
		echo "Result: Can't tell, ask your host"
		echo "No PHP program was found on this machine for this user. If your website runs PHP, it may"
		echo "be on a different server, or in a container. Ask your host, using the email in the guide."
		return 3
	fi

	# Running website PHP that was updated on disk but not restarted shows as "(deleted)".
	stale=0
	for d in /proc/[0-9]*; do
		exe=$(readlink "$d/exe" 2>/dev/null) || continue
		case "$exe" in
			*php*" (deleted)"|*lsphp*" (deleted)"|*frankenphp*" (deleted)") stale=1 ;;
		esac
	done 2>/dev/null
	if [ "$stale" -eq 1 ]; then
		echo "Restart needed: a running PHP process is still using a program that has since been"
		echo "replaced on disk. Restart PHP (all PHP-FPM workers, or Apache) so the update takes effect."
		echo
		[ "$worst" = patched ] && worst=canttell
	fi

	# Settings from the advisory, read from command-line PHP. Your website may use other values.
	if [ -n "$cli_bin" ]; then
		settings=$("$cli_bin" -r '$ks = ["session.upload_progress.enabled","memory_limit","post_max_size"]; if (PHP_MAJOR_VERSION == 8 && PHP_MINOR_VERSION == 5) $ks[] = "fatal_error_backtraces"; foreach ($ks as $k) { $v = ini_get($k); echo $k, "=", ($v === false ? "(not in this version)" : ($v === "" ? "0" : $v)), "\n"; }' 2>/dev/null)
		if [ -n "$settings" ]; then
			echo "Settings named in the advisory (command-line PHP; your website may use different ones):"
			printf '%s\n' "$settings" | sed 's/^/  /'
			case "$settings" in
				*"session.upload_progress.enabled=1"*)
					echo "  Tip: until PHP's next regular release, PHP suggests session.upload_progress.enabled=0"
					echo "  (informational advisory CVE-2026-115560, 23 October 2026, which only matters for"
					echo "  unusual setups). Set it in php.ini or the server config, not with ini_set() or"
					echo "  .user.ini, then restart PHP. If your host already did this for the 21 October fix,"
					echo "  nothing more is needed." ;;
			esac
			echo
		fi
	fi

	only_patched=no
	[ "$worst" = patched ] && only_patched=yes
	if [ "$web_found" -eq 0 ]; then
		[ "$worst" = patched ] && worst=canttell
	fi

	echo "Overall: $(say_result "$worst")"
	if [ "$worst" = canttell ] && [ "$web_found" -eq 0 ] && [ "$stale" -eq 0 ] && [ "$only_patched" = yes ]; then
		echo "Command-line PHP here is patched, but this check couldn't find the PHP your website uses."
		echo "Check the website's own version in your control panel, with the upload check, or by"
		echo "sending your host the email in the guide."
		return 2
	fi
	case "$worst" in
		patched) echo "Every PHP this check found includes the fix."; return 0 ;;
		update)
			echo "Update PHP, then restart it. On shared or managed hosting, ask your host to do it,"
			echo "using the email in the guide. If they say they've added a backported fix, that's fine too."
			return 1 ;;
		*)
			echo "The version number alone can't settle it. Send your host the email in the guide and"
			echo "ask them to confirm both fixes are in and PHP has been restarted."
			return 2 ;;
	esac
}

# Tests source this file with PHP2SHELL_LIB=1 to use classify_version without running the check.
if [ "${PHP2SHELL_LIB:-}" != 1 ]; then
	main "$@"
	exit $?
fi
