#!/usr/bin/env bash
# =====================================================================
#  appdogu-check.sh    버전 / version 2026.11.18-2
#
#  [한국어]
#  리눅스 서버 보안 점검 파일이에요.
#  - 읽기만 해요. 설정이나 파일을 바꾸거나 지우거나 설치하지 않아요.
#  - 바깥으로 아무것도 보내지 않아요. 결과 전송도, 버전 확인 요청도 없어요.
#  - 업데이트는 서버에 이미 받아 둔 패키지 목록 기준으로만 봐요.
#  - 결과는 화면과 appdogu-check-<날짜시각>.txt 파일 하나에 남아요.
#  실행:   sudo bash appdogu-check.sh
#  옵션:   --lang en        영어로 보기
#          --web <폴더>     웹 폴더 직접 지정 (여러 번 쓸 수 있어요)
#          --quick          웹쉘 찾기 건너뛰기
#          --help           도움말
#
#  [English]
#  Linux server security check.
#  - Read-only. It changes, deletes or installs nothing.
#  - Sends nothing over the network.
#  - Updates are checked against the package lists already on the server.
#  Usage:  sudo bash appdogu-check.sh [--lang en] [--web DIR]... [--quick] [--help]
# =====================================================================

VER="2026.11.18-2"
PHP_TABLE_DATE="2026-11-18"
SCAN_LIMIT=900
MAX_LIST=200

export LC_ALL=C
umask 077
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"

LANG_SEL="ko"
QUICK=0
WEB_ARGS=()

t() { if [ "$LANG_SEL" = "en" ]; then printf '%s' "$2"; else printf '%s' "$1"; fi; }

usage() {
	if [ "$LANG_SEL" = "en" ]; then
		cat <<'EOF'
appdogu-check.sh - Linux server security check (read-only, no network)

  sudo bash appdogu-check.sh [options]

  --lang en       English output (default: Korean)
  --web DIR       Web folder to scan (can be used many times)
  --quick         Skip the web shell scan
  --help          Show this help

Result: screen + appdogu-check-<date-time>.txt in the current folder (or /tmp).
EOF
	else
		cat <<'EOF'
appdogu-check.sh - 보안지키미 · 리눅스 서버 보안 점검 (읽기만 함 · 바깥 전송 없음)

  sudo bash appdogu-check.sh [옵션]

  --lang en       영어로 보기 (기본은 한국어)
  --web 폴더      웹쉘을 찾을 웹 폴더 (여러 번 쓸 수 있어요)
  --quick         웹쉘 찾기 건너뛰기
  --help          이 도움말

결과: 화면 + 지금 폴더(쓸 수 없으면 /tmp)의 appdogu-check-<날짜시각>.txt
EOF
	fi
}

for a in "$@"; do
	case "$a" in --lang=en) LANG_SEL="en" ;; esac
done
prev=""
for a in "$@"; do
	[ "$prev" = "--lang" ] && [ "$a" = "en" ] && LANG_SEL="en"
	prev="$a"
done

while [ $# -gt 0 ]; do
	case "$1" in
		--lang)
			[ $# -ge 2 ] || { usage; exit 2; }
			shift 2 ;;
		--lang=*) shift ;;
		--web)
			[ $# -ge 2 ] || { usage; exit 2; }
			WEB_ARGS+=("$2"); shift 2 ;;
		--web=*) WEB_ARGS+=("${1#*=}"); shift ;;
		--quick) QUICK=1; shift ;;
		-h|--help) usage; exit 0 ;;
		*) printf '%s: %s\n\n' "$(t "모르는 옵션" "Unknown option")" "$1" >&2; usage >&2; exit 2 ;;
	esac
done

has() { command -v "$1" >/dev/null 2>&1; }

IS_ROOT=0
[ "$(id -u)" = "0" ] && IS_ROOT=1

TODAY=$(date +%Y-%m-%d)
STAMP=$(date +%Y%m%d-%H%M%S)

COLOR=0
[ -t 1 ] && COLOR=1

declare -A CNT=([crit]=0 [high]=0 [med]=0 [low]=0 [pass]=0 [unk]=0)
OUT_LINES=()

sev_label() {
	case "$1" in
		crit) t "긴급" "Critical" ;;
		high) t "중요" "High" ;;
		med)  t "보통" "Medium" ;;
		low)  t "참고" "Low" ;;
		pass) t "통과" "Pass" ;;
		*)    t "확인 못 함" "Unknown" ;;
	esac
}

sev_color() {
	case "$1" in
		crit) printf '1;31' ;;
		high) printf '31' ;;
		med)  printf '33' ;;
		low)  printf '36' ;;
		pass) printf '32' ;;
		*)    printf '35' ;;
	esac
}

fix_url() {
	local id
	id=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
	if [ "$LANG_SEL" = "en" ]; then
		printf 'https://appdogu.com/learn/security/fix/%s' "$id"
	else
		printf 'https://appdogu.com/ko/learn/security/fix/%s' "$id"
	fi
}

say() {
	OUT_LINES+=("$1")
	printf '%s\n' "$1"
}

add() {
	local sev=$1 id=$2 msg=$3 label url
	CNT[$sev]=$(( ${CNT[$sev]} + 1 ))
	label=$(sev_label "$sev")
	url=$(fix_url "$id")
	OUT_LINES+=("[$label] $id $msg → $url")
	if [ "$COLOR" = "1" ]; then
		printf '\033[%sm[%s]\033[0m %s %s → %s\n' "$(sev_color "$sev")" "$label" "$id" "$msg" "$url"
	else
		printf '[%s] %s %s → %s\n' "$label" "$id" "$msg" "$url"
	fi
}

detail() {
	OUT_LINES+=("        - $1")
	printf '        - %s\n' "$1"
}

step() {
	printf '  ... %s\n' "$1" >&2
}

hx() {
	local s=$1 o="" i
	for ((i = 0; i < ${#s}; i += 2)); do o+="\\x${s:i:2}"; done
	printf '%b' "$o"
}

ver_lt() {
	local -a a b
	local i n x y
	IFS='._-' read -r -a a <<<"$1"
	IFS='._-' read -r -a b <<<"$2"
	n=${#a[@]}
	[ ${#b[@]} -gt "$n" ] && n=${#b[@]}
	for ((i = 0; i < n; i++)); do
		x=${a[i]:-0}; y=${b[i]:-0}
		x=${x%%[!0-9]*}; y=${y%%[!0-9]*}
		x=$((10#${x:-0})); y=$((10#${y:-0}))
		[ "$x" -lt "$y" ] && return 0
		[ "$x" -gt "$y" ] && return 1
	done
	return 1
}

days_until() {
	local a b
	a=$(date -d "$1" +%s 2>/dev/null) || return 1
	b=$(date -d "$TODAY" +%s 2>/dev/null) || return 1
	echo $(( (a - b) / 86400 ))
}

is_on() {
	case "$(printf '%s' "$1" | tr 'A-Z' 'a-z')" in
		on|1|yes|true|stdout) return 0 ;;
	esac
	return 1
}

# ---------------------------------------------------------------------
# PHP 버전 비교표 / PHP version table (기준일 PHP_TABLE_DATE)
#   줄 버전 : PHP 공식 보안 지원이 끝나는 날
#   CVE-2024-4577 (윈도우 PHP-CGI 인자 주입) 은 윈도우에서만 해당해서
#   리눅스 점검에서는 쓰지 않아요.
# ---------------------------------------------------------------------
php_eol_date() {
	case "$1" in
		5.*|7.*) echo "2022-11-28" ;;
		8.0) echo "2023-11-26" ;;
		8.1) echo "2025-12-31" ;;
		8.2) echo "2026-12-31" ;;
		8.3) echo "2027-12-31" ;;
		8.4) echo "2028-12-31" ;;
		8.5) echo "2029-12-31" ;;
		*) echo "" ;;
	esac
}

# ---------------------------------------------------------------------
# PHP2SHELL 고친 버전 / fixed releases (2026-10-21 공개)
#   CVE-2026-109618 (9.8) · CVE-2026-109619 (8.1) 원격 코드 실행
#   이 버전보다 낮으면 위험 · 8.1 이하는 공식 고친 버전이 없음
# ---------------------------------------------------------------------
php_fixed_ver() {
	case "$1" in
		8.2) echo "8.2.35" ;;
		8.3) echo "8.3.36" ;;
		8.4) echo "8.4.27" ;;
		8.5) echo "8.5.12" ;;
		*) echo "" ;;
	esac
}

# ---------------------------------------------------------------------
# 웹쉘 찾기 규칙 / web shell rules
#   보안 프로그램이 이 점검 파일을 악성으로 잘못 잡지 않도록
#   규칙 낱말은 16진수로 적고 실행할 때 풀어요.
# ---------------------------------------------------------------------
W_EVAL=$(hx 6576616c)
W_ASSERT=$(hx 617373657274)
W_B64=$(hx 6261736536345f6465636f6465)
W_GZI=$(hx 677a696e666c617465)
W_GZU=$(hx 677a756e636f6d7072657373)
W_GZD=$(hx 677a6465636f6465)
W_ROT=$(hx 7374725f726f743133)
W_SYS=$(hx 73797374656d)
W_PASS=$(hx 7061737374687275)
W_SHX=$(hx 7368656c6c5f65786563)
W_EXEC=$(hx 65786563)
W_POPEN=$(hx 706f70656e)
W_PROC=$(hx 70726f635f6f70656e)
W_PCNTL=$(hx 70636e746c5f65786563)
W_PREG=$(hx 707265675f7265706c616365)
W_CF=$(hx 6372656174655f66756e6374696f6e)
W_SIG="$(hx 46696c65734d616e)|$(hx 6339397368656c6c)|$(hx 7235377368656c6c)|$(hx 623337346b)|$(hx 496e646f58706c6f6974)"
SG='\$('"$(hx 5f474554)|$(hx 5f504f5354)|$(hx 5f52455155455354)|$(hx 5f434f4f4b4945)"')'
SP='[[:space:]]*'
NB='(^|[^a-z0-9_>:$])'

declare -A RULE
RULE[eval_decode]="${W_EVAL}${SP}\\(${SP}(@${SP})?(${W_B64}|${W_GZI}|${W_GZU}|${W_GZD}|${W_ROT})${SP}\\("
RULE[eval_input]="${W_EVAL}${SP}\\(${SP}(@${SP})?${SG}"
RULE[assert_input]="${W_ASSERT}${SP}\\(${SP}(@${SP})?${SG}"
RULE[exec_input]="${NB}(${W_SYS}|${W_PASS}|${W_SHX}|${W_EXEC}|${W_POPEN}|${W_PROC}|${W_PCNTL})${SP}\\([^;)]{0,40}${SG}"
RULE[backtick_input]='(=|\(|echo|print|return)'"${SP}"'`'"${SP}${SG}"
RULE[call_input]="${SG}${SP}\\[[^]]{1,40}\\]${SP}\\("
RULE[preg_e]="${W_PREG}${SP}\\(${SP}['\"](/[^/]*/|#[^#]*#|~[^~]*~|@[^@]*@)[a-z]*e[a-z]*['\"]"
RULE[shell_marker]="(${W_SIG})"
RULE[create_function]="${W_CF}${SP}\\("
RULE[hex_payload]='(\\x[0-9a-f]{2}){10}'
LONG_RUN='[A-Za-z0-9+/]{400}'
STRONG_RULES="eval_decode eval_input assert_input exec_input backtick_input call_input preg_e"
WEAK_RULES="shell_marker create_function hex_payload"
HEX_NEED="${SG}|(${W_EVAL}|${W_ASSERT})${SP}\\("
HT_RULE="(AddType|AddHandler)[^#]*php[^#]*[[:space:]]\\.?(jpe?g|png|gif|ico|txt|bmp|webp|svg)([[:space:]]|$)"

# ---------------------------------------------------------------------
# 머리 / header
# ---------------------------------------------------------------------
OS_NAME="?"
if [ -r /etc/os-release ]; then
	OS_NAME=$(. /etc/os-release 2>/dev/null; printf '%s' "${PRETTY_NAME:-${NAME:-?}}")
fi
KERNEL=$(uname -r 2>/dev/null)

say "=================================================================="
say " appdogu $(t "보안지키미" "security check") $VER"
say "=================================================================="
say "$(t "점검 시각" "Checked at"): $(date '+%Y-%m-%d %H:%M:%S')"
say "$(t "운영체제" "OS"): $OS_NAME ($(t "커널" "kernel") $KERNEL)"
if [ "$IS_ROOT" = "1" ]; then
	say "$(t "권한" "Privilege"): root"
else
	say "$(t "권한" "Privilege"): $(t "일반 사용자 (root 로 다시 돌리면 더 봐요: sudo bash appdogu-check.sh)" "normal user (run again as root to see more: sudo bash appdogu-check.sh)")"
fi
say "$(t "PHP 버전 기준일" "PHP version table date"): $PHP_TABLE_DATE"
say "$(t "이 점검은 읽기만 하고 바깥으로 아무것도 보내지 않아요." "This check is read-only and sends nothing over the network.")"
say "------------------------------------------------------------------"

# ---------------------------------------------------------------------
# 웹 폴더 / web folders
# ---------------------------------------------------------------------
WEB_ROOTS=()
collect_web_roots() {
	local cand=() d e keep r
	if [ ${#WEB_ARGS[@]} -gt 0 ]; then
		cand=("${WEB_ARGS[@]}")
	else
		cand=(/var/www /usr/share/nginx/html /srv/www)
		for d in /home/*/public_html; do cand+=("$d"); done
	fi
	for d in "${cand[@]}"; do
		[ -d "$d" ] || continue
		d=$(readlink -f "$d" 2>/dev/null || printf '%s' "$d")
		keep=1
		for e in "${WEB_ROOTS[@]}"; do
			case "$d/" in "$e"/*) keep=0 ;; esac
		done
		[ "$keep" = "1" ] || continue
		r=()
		for e in "${WEB_ROOTS[@]}"; do
			case "$e/" in "$d"/*) ;; *) r+=("$e") ;; esac
		done
		WEB_ROOTS=("${r[@]}" "$d")
	done
}
collect_web_roots

# =====================================================================
# P02 ~ P06 : PHP
# =====================================================================
PHP_BINS=()
find_php_bins() {
	local c real b seen="|"
	for c in "$(command -v php 2>/dev/null)" /usr/bin/php* /usr/sbin/php-fpm* /usr/local/bin/php* /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/plesk/php/*/bin/php /www/server/php/*/bin/php /usr/local/php*/bin/php \
		/usr/local/lsws/lsphp*/bin/php /usr/local/lsws/lsphp*/bin/lsphp /opt/alt/php*/usr/bin/php; do
		[ -n "$c" ] && [ -f "$c" ] && [ -x "$c" ] || continue
		b=$(basename "$c")
		[[ "$b" =~ ^(php[0-9.]*|php-fpm[0-9.]*|php-cgi[0-9.]*|lsphp[0-9.]*)$ ]] || continue
		real=$(readlink -f "$c" 2>/dev/null || printf '%s' "$c")
		case "$seen" in *"|$real|"*) continue ;; esac
		seen="$seen$real|"
		PHP_BINS+=("$real")
	done
}

php_version_of() {
	local out
	if has timeout; then
		out=$(timeout 10 "$1" -n -v 2>/dev/null | head -n 1)
	else
		out=$("$1" -n -v 2>/dev/null | head -n 1)
	fi
	if [[ "$out" =~ ^PHP[[:space:]]+([0-9]+\.[0-9]+\.[0-9]+) ]]; then
		printf '%s' "${BASH_REMATCH[1]}"
	fi
}

php_pkg_source() {
	local f=$1 pkg v vendor
	if has dpkg-query && has dpkg; then
		pkg=$(dpkg -S "$f" 2>/dev/null | head -n 1 | cut -d: -f1)
		if [ -n "$pkg" ]; then
			v=$(dpkg-query -W -f='${Version}' "$pkg" 2>/dev/null)
			case "$v" in
				*sury*) echo "thirdparty" ;;
				*) echo "distro" ;;
			esac
			return
		fi
	fi
	if has rpm; then
		vendor=$(rpm -qf --qf '%{VENDOR}' "$f" 2>/dev/null | head -n 1)
		if [ -n "$vendor" ] && ! printf '%s' "$vendor" | grep -qi 'not owned'; then
			case "$vendor" in
				*Remi*|*remi*|"(none)") echo "thirdparty" ;;
				*) echo "distro" ;;
			esac
			return
		fi
	fi
	echo "none"
}

check_php_versions() {
	step "$(t "PHP 버전" "PHP version")"
	find_php_bins
	if [ ${#PHP_BINS[@]} -eq 0 ]; then
		add pass P02 "$(t "PHP 가 안 보여요" "No PHP found")"
		return
	fi
	local b v mm eol left src i fixv need hit
	local vlist=() vb=()
	declare -A VBINS=()
	for b in "${PHP_BINS[@]}"; do
		v=$(php_version_of "$b")
		if [ -z "$v" ]; then
			add unk P02 "$(t "PHP 버전을 읽지 못했어요" "Could not read the PHP version"): $b"
			continue
		fi
		if [ -z "${VBINS[$v]:-}" ]; then
			vlist+=("$v"); vb+=("$b"); VBINS[$v]="$b"
		else
			VBINS[$v]="${VBINS[$v]}, $b"
		fi
	done
	for ((i = 0; i < ${#vlist[@]}; i++)); do
		v=${vlist[$i]}
		b=${VBINS[$v]}
		mm=${v%.*}
		eol=$(php_eol_date "$mm")
		if [ -z "$eol" ]; then
			add low P02 "PHP $v ($b) $(t "는 비교표에 없는 버전이에요. 버전만 알려 드려요" "is not in the version table. Version only")"
			continue
		fi
		left=$(days_until "$eol")
		src=$(php_pkg_source "${vb[$i]}")
		fixv=$(php_fixed_ver "$mm")
		hit=0
		if { [ -n "$fixv" ] && ver_lt "$v" "$fixv"; } || { [ -z "$fixv" ] && ver_lt "$mm" "8.2"; }; then
			if [ -n "$fixv" ]; then
				need="$fixv $(t "이상" "or later")"
			else
				need="8.2.35 $(t "이상(지원 중인 줄)" "or later (a supported branch)")"
			fi
			if [ "$src" = "distro" ]; then
				add high P02 "PHP $v ($b) $(t "는 PHP2SHELL(CVE-2026-109618·CVE-2026-109619) 원격 코드 실행에 걸리는 버전 번호예요. 배포판 패키지는 버전 번호가 그대로여도 고친 내용이 들어갈 수 있으니, 배포판 보안 업데이트가 깔렸는지 꼭 확인하세요" "has a version number hit by PHP2SHELL (CVE-2026-109618, CVE-2026-109619) remote code execution. Distro packages can carry the fix without changing the version, so make sure the distro security update is installed")"
			else
				add crit P02 "PHP $v ($b) $(t "는 PHP2SHELL(CVE-2026-109618·CVE-2026-109619) 원격 코드 실행에 걸리는 버전이에요. ${need}으로 올리세요" "is hit by PHP2SHELL (CVE-2026-109618, CVE-2026-109619) remote code execution. Upgrade to ${need}")"
			fi
			hit=1
		fi
		if [ -n "$left" ] && [ "$left" -lt 0 ]; then
			if [ "$src" = "distro" ]; then
				add med P02 "PHP $v ($b) $(t "는 PHP 공식 지원이 ${eol} 에 끝났어요. 배포판 패키지라 배포판이 보안 수정을 따로 낼 수 있으니 배포판 지원 기간을 확인하세요" "reached PHP end of life on ${eol}. It is a distro package, so the distro may still ship security fixes. Check the distro support period")"
			else
				add high P02 "PHP $v ($b) $(t "는 공식 보안 지원이 ${eol} 에 끝난 버전이에요" "reached end of security support on ${eol}")"
			fi
		elif [ -n "$left" ] && [ "$left" -le 60 ]; then
			add low P02 "PHP $v ($b) $(t "는 공식 보안 지원이 ${eol} 에 끝나요" "security support ends on ${eol}")"
		elif [ "$hit" = "0" ]; then
			add pass P02 "PHP $v ($b) $(t "는 지원 중인 버전이에요 (같은 줄의 최신 버전인지는 따로 확인)" "is a supported branch (check that it is the newest patch release)")"
		fi
	done
}

INI_SETS=()
find_ini_sets() {
	local d s
	for d in /etc/php/*/*/; do
		d=${d%/}
		s=$(basename "$d")
		case "$s" in cli|mods-available) continue ;; esac
		[ -f "$d/php.ini" ] && INI_SETS+=("$d/php.ini|$d/conf.d|$d/pool.d")
	done
	[ -f /etc/php.ini ] && INI_SETS+=("/etc/php.ini|/etc/php.d|/etc/php-fpm.d")
	for d in /etc/opt/remi/php*; do
		[ -f "$d/php.ini" ] && INI_SETS+=("$d/php.ini|$d/php.d|$d/php-fpm.d")
	done
	if [ -f /usr/local/etc/php/php.ini ]; then
		INI_SETS+=("/usr/local/etc/php/php.ini|/usr/local/etc/php/conf.d|/usr/local/etc/php-fpm.d")
	elif [ -d /usr/local/etc/php/conf.d ]; then
		INI_SETS+=("|/usr/local/etc/php/conf.d|/usr/local/etc/php-fpm.d")
	fi
	[ -f /usr/local/lib/php.ini ] && INI_SETS+=("/usr/local/lib/php.ini||")
	for d in /usr/local/php*/etc /www/server/php/*/etc /opt/cpanel/ea-php*/root/etc /opt/plesk/php/*/etc /opt/alt/php*/etc /usr/local/lsws/lsphp*/etc/php/*/litespeed; do
		[ -f "$d/php.ini" ] && INI_SETS+=("$d/php.ini|$d/php.d|$d/php-fpm.d")
	done
}

ini_last() {
	local key=$1
	shift
	[ $# -gt 0 ] || return 1
	awk -v k="$key" '
		{
			line = $0
			sub(/^[ \t]+/, "", line)
			if (line == "" || line ~ /^[;#\[]/) next
			p = index(line, "=")
			if (p == 0) next
			name = substr(line, 1, p - 1)
			sub(/[ \t]+$/, "", name)
			if (name != k) next
			val = substr(line, p + 1)
			sub(/^[ \t]+/, "", val)
			if (val ~ /^"/) {
				val = substr(val, 2)
				q = index(val, "\"")
				if (q > 0) val = substr(val, 1, q - 1)
			} else {
				c = index(val, ";")
				if (c > 0) val = substr(val, 1, c - 1)
				sub(/[ \t\r]+$/, "", val)
			}
			found = 1
			last = val
		}
		END { if (found) { print last; exit 0 } exit 1 }
	' "$@" 2>/dev/null
}

pool_last() {
	local key=$1 f=$2
	awk -v k="$key" '
		{
			line = $0
			sub(/^[ \t]+/, "", line)
			if (line ~ /^[;#]/) next
			p = index(line, "=")
			if (p == 0) next
			name = substr(line, 1, p - 1)
			sub(/[ \t]+$/, "", name)
			if (name != "php_admin_value[" k "]" && name != "php_value[" k "]" && name != "php_admin_flag[" k "]" && name != "php_flag[" k "]") next
			val = substr(line, p + 1)
			sub(/^[ \t]+/, "", val)
			c = index(val, ";")
			if (c > 0) val = substr(val, 1, c - 1)
			sub(/[ \t\r]+$/, "", val)
			gsub(/^"|"$/, "", val)
			found = 1
			last = val
		}
		END { if (found) { print last; exit 0 } exit 1 }
	' "$f" 2>/dev/null
}

check_php_ini() {
	step "$(t "php.ini 설정" "php.ini settings")"
	find_ini_sets
	if [ ${#INI_SETS[@]} -eq 0 ]; then
		if [ ${#PHP_BINS[@]} -gt 0 ]; then
			local id
			for id in P03 P04 P05 P06; do
				add unk "$id" "$(t "웹에서 쓰는 php.ini 를 못 찾았어요" "Could not find a php.ini used by the web server")"
			done
		else
			add pass P03 "$(t "PHP 가 안 보여요" "No PHP found")"
		fi
		return
	fi

	local set ini scan pool files f label pv
	local CTX=() CTXV_AUI=() CTXV_DF=() CTXV_EXP=() CTXV_DE=()
	for set in "${INI_SETS[@]}"; do
		IFS='|' read -r ini scan pool <<<"$set"
		files=()
		[ -n "$ini" ] && [ -r "$ini" ] && files+=("$ini")
		if [ -n "$scan" ] && [ -d "$scan" ]; then
			for f in "$scan"/*.ini; do [ -r "$f" ] && files+=("$f"); done
		fi
		local base_aui base_df base_exp base_de
		base_aui=$(ini_last allow_url_include "${files[@]}") || base_aui="Off"
		base_df=$(ini_last disable_functions "${files[@]}") || base_df=""
		base_exp=$(ini_last expose_php "${files[@]}") || base_exp="On"
		base_de=$(ini_last display_errors "${files[@]}") || base_de="On"
		label=${ini:-$scan}
		local pools=()
		if [ -n "$pool" ] && [ -d "$pool" ]; then
			for f in "$pool"/*.conf; do [ -r "$f" ] && pools+=("$f"); done
		fi
		if [ ${#pools[@]} -eq 0 ]; then
			CTX+=("$label"); CTXV_AUI+=("$base_aui"); CTXV_DF+=("$base_df"); CTXV_EXP+=("$base_exp"); CTXV_DE+=("$base_de")
		else
			for f in "${pools[@]}"; do
				CTX+=("$label + $f")
				pv=$(pool_last allow_url_include "$f") || pv=$base_aui; CTXV_AUI+=("$pv")
				pv=$(pool_last disable_functions "$f") || pv=$base_df; CTXV_DF+=("$pv")
				pv=$(pool_last expose_php "$f") || pv=$base_exp; CTXV_EXP+=("$pv")
				pv=$(pool_last display_errors "$f") || pv=$base_de; CTXV_DE+=("$pv")
			done
		fi
	done

	local i n=${#CTX[@]} want missing df bad3=() bad4=() part4=() bad5=() bad6=()
	for ((i = 0; i < n; i++)); do
		is_on "${CTXV_AUI[$i]}" && bad3+=("${CTX[$i]}")
		df=",$(printf '%s' "${CTXV_DF[$i]}" | tr -d ' \t' | tr 'A-Z' 'a-z'),"
		missing=""
		local hit=0
		for want in exec system passthru shell_exec proc_open popen; do
			case "$df" in *",$want,"*) hit=$((hit + 1)) ;; *) missing="$missing $want" ;; esac
		done
		if [ "$hit" -eq 0 ]; then
			bad4+=("${CTX[$i]}")
		elif [ -n "$missing" ]; then
			part4+=("${CTX[$i]} ($(t "안 막힘" "not blocked"):$missing)")
		fi
		is_on "${CTXV_EXP[$i]}" && bad5+=("${CTX[$i]}")
		is_on "${CTXV_DE[$i]}" && bad6+=("${CTX[$i]}")
	done

	if [ ${#bad3[@]} -gt 0 ]; then
		add high P03 "$(t "allow_url_include 가 켜져 있어요" "allow_url_include is On")"
		for f in "${bad3[@]}"; do detail "$f"; done
	else
		add pass P03 "$(t "allow_url_include 가 꺼져 있어요" "allow_url_include is Off")"
	fi
	if [ ${#bad4[@]} -gt 0 ]; then
		add med P04 "$(t "disable_functions 에 exec·system 같은 명령 실행 함수가 없어요" "disable_functions does not block exec, system and similar functions")"
		for f in "${bad4[@]}"; do detail "$f"; done
	fi
	if [ ${#part4[@]} -gt 0 ]; then
		add low P04 "$(t "disable_functions 에 일부 함수가 빠졌어요" "disable_functions misses some functions")"
		for f in "${part4[@]}"; do detail "$f"; done
	fi
	if [ ${#bad4[@]} -eq 0 ] && [ ${#part4[@]} -eq 0 ]; then
		add pass P04 "$(t "disable_functions 가 명령 실행 함수를 막고 있어요" "disable_functions blocks command functions")"
	fi
	if [ ${#bad5[@]} -gt 0 ]; then
		add low P05 "$(t "expose_php 가 켜져 있어 PHP 버전이 응답 머리에 보여요" "expose_php is On, so the PHP version shows in response headers")"
		for f in "${bad5[@]}"; do detail "$f"; done
	else
		add pass P05 "$(t "expose_php 가 꺼져 있어요" "expose_php is Off")"
	fi
	if [ ${#bad6[@]} -gt 0 ]; then
		add med P06 "$(t "display_errors 가 켜져 있어 오류 내용이 방문자에게 보일 수 있어요" "display_errors is On, so visitors may see error details")"
		for f in "${bad6[@]}"; do detail "$f"; done
	else
		add pass P06 "$(t "display_errors 가 꺼져 있어요" "display_errors is Off")"
	fi
}

# =====================================================================
# P07 : 업로드 폴더 안 PHP / PHP inside upload folders
# =====================================================================
WEB_USERS="www-data apache nginx nobody http lighttpd wwwrun www"
UPLOAD_DIRS=()
check_upload_php() {
	step "$(t "업로드 폴더" "upload folders")"
	if [ ${#WEB_ROOTS[@]} -eq 0 ]; then
		add unk P07 "$(t "웹 폴더를 못 찾았어요 (--web 으로 알려 주세요)" "No web folder found (use --web)")"
		return
	fi
	local r d top_owner owner perm writable f size hits=() n=0
	while IFS= read -r -d '' d; do
		UPLOAD_DIRS+=("$d")
	done < <(find "${WEB_ROOTS[@]}" \( -name .git -o -name node_modules -o -name vendor -o -name wp-includes -o -name wp-admin \
		-o -name plugins -o -name themes -o -name src -o -name lib -o -name libs -o -name includes \) -prune -o -type d \
		\( -name uploads -o -name upload -o -name files -o -name data -o -name attach -o -name attachments -o -name userfiles \) -print0 2>/dev/null)

	for d in "${UPLOAD_DIRS[@]}"; do
		writable=0
		read -r owner perm < <(stat -c '%U %a' "$d" 2>/dev/null)
		[ -n "$perm" ] || continue
		case "$perm" in *[2367]) writable=1 ;; esac
		case " $WEB_USERS " in *" $owner "*) writable=1 ;; esac
		for r in "${WEB_ROOTS[@]}"; do
			case "$d/" in
				"$r"/*)
					top_owner=$(stat -c '%U' "$r" 2>/dev/null)
					[ -n "$top_owner" ] && [ "$top_owner" != "root" ] && [ "$top_owner" = "$owner" ] && writable=1
					;;
			esac
		done
		[ "$writable" = "1" ] || continue
		while IFS= read -r -d '' f; do
			size=$(stat -c '%s' "$f" 2>/dev/null)
			if [ "$(basename "$f")" = "index.php" ] && [ "${size:-0}" -le 100 ]; then
				continue
			fi
			n=$((n + 1))
			[ ${#hits[@]} -lt "$MAX_LIST" ] && hits+=("$f")
		done < <(find "$d" -type f \( -iname '*.php' -o -iname '*.phtml' -o -iname '*.phar' -o -iname '*.php[0-9]' -o -iname '*.pht' \) -print0 2>/dev/null)
	done
	if [ "$n" -gt 0 ]; then
		add high P07 "$(t "쓰기 가능한 업로드 폴더 안에 PHP 파일이 ${n}개 있어요" "${n} PHP file(s) inside writable upload folders")"
		for f in "${hits[@]}"; do detail "$f"; done
	else
		add pass P07 "$(t "쓰기 가능한 업로드 폴더 안에 PHP 파일이 없어요" "No PHP files inside writable upload folders")"
	fi
}

# =====================================================================
# P01 : 웹쉘 의심 파일 / suspected web shells
# =====================================================================
check_webshell() {
	if [ "$QUICK" = "1" ]; then
		add unk P01 "$(t "--quick 이라 웹쉘 찾기를 건너뛰었어요" "Web shell scan skipped (--quick)")"
		return
	fi
	if [ ${#WEB_ROOTS[@]} -eq 0 ]; then
		add unk P01 "$(t "웹 폴더를 못 찾았어요 (--web 으로 알려 주세요)" "No web folder found (use --web)")"
		return
	fi
	step "$(t "웹쉘 찾기 (오래 걸릴 수 있어요, 최대 ${SCAN_LIMIT}초)" "web shell scan (may take a while, up to ${SCAN_LIMIT}s)")"
	local r
	for r in "${WEB_ROOTS[@]}"; do step "  $r"; done

	local tcmd=() cands=() f t0
	has timeout && tcmd=(timeout "$SCAN_LIMIT")
	t0=$SECONDS
	local gargs=(-l -Z -I -i -E)
	local name
	for name in $STRONG_RULES $WEAK_RULES; do gargs+=(-e "${RULE[$name]}"); done
	gargs+=(-e "$LONG_RUN")

	while IFS= read -r -d '' f; do
		cands+=("$f")
	done < <(find "${WEB_ROOTS[@]}" \( -name .git -o -name node_modules -o -path '*/vendor/*/tests' -o -path '*/vendor/*/test' \) -prune -o \
		-type f \( -iname '*.php' -o -iname '*.phtml' -o -iname '*.php[0-9]' -o -iname '*.pht' -o -iname '*.phar' -o -iname '*.inc' \) \
		-size -5120k -print0 2>/dev/null | "${tcmd[@]}" xargs -0 -r grep "${gargs[@]}" -- 2>/dev/null)
	if [ ${#tcmd[@]} -gt 0 ] && [ $((SECONDS - t0)) -ge "$SCAN_LIMIT" ]; then
		add unk P01 "$(t "웹쉘 찾기가 ${SCAN_LIMIT}초를 넘어 중간에 멈췄어요. --web 으로 폴더를 나눠 다시 돌려 보세요" "Web shell scan stopped after ${SCAN_LIMIT}s. Run again with smaller --web folders")"
	fi

	local strong=() weak=() hits h
	for f in "${cands[@]}"; do
		hits=""
		for name in $STRONG_RULES; do
			grep -q -I -i -E -e "${RULE[$name]}" -- "$f" 2>/dev/null && hits="$hits, $name"
		done
		if grep -q -I -E -e "$LONG_RUN" -- "$f" 2>/dev/null; then
			if grep -q -I -i -E -e "(${W_EVAL}|${W_ASSERT})${SP}\\(" -- "$f" 2>/dev/null; then
				hits="$hits, packed_eval"
			fi
		fi
		if [ -n "$hits" ]; then
			strong+=("$f (${hits#, })")
			continue
		fi
		for name in $WEAK_RULES; do
			grep -q -I -i -E -e "${RULE[$name]}" -- "$f" 2>/dev/null || continue
			if [ "$name" = "hex_payload" ]; then
				grep -q -I -i -E -e "$HEX_NEED" -- "$f" 2>/dev/null || continue
			fi
			hits="$hits, $name"
		done
		if grep -q -I -E -e "$LONG_RUN" -- "$f" 2>/dev/null && grep -q -I -i -E -e "(${W_B64}|${W_GZI}|${W_ROT})${SP}\\(" -- "$f" 2>/dev/null; then
			hits="$hits, packed"
		fi
		[ -n "$hits" ] && weak+=("$f (${hits#, })")
	done

	local ht=() img=()
	while IFS= read -r -d '' f; do
		ht+=("$f (htaccess_handler)")
	done < <(find "${WEB_ROOTS[@]}" \( -name .git -o -name node_modules \) -prune -o -type f -name .htaccess -size -1024k -print0 2>/dev/null \
		| xargs -0 -r grep -l -Z -i -E -e "$HT_RULE" -- 2>/dev/null)
	if [ ${#UPLOAD_DIRS[@]} -gt 0 ]; then
		while IFS= read -r -d '' f; do
			img+=("$f (php_in_image)")
		done < <(find "${UPLOAD_DIRS[@]}" -type f \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.ico' -o -iname '*.bmp' -o -iname '*.webp' \) \
			-size -5120k -print0 2>/dev/null | "${tcmd[@]}" xargs -0 -r grep -l -Z -a -F -e '<?php' -- 2>/dev/null)
	fi

	local all_strong=("${strong[@]}" "${ht[@]}" "${img[@]}") shown=0
	if [ ${#all_strong[@]} -gt 0 ]; then
		add crit P01 "$(t "웹쉘로 의심되는 파일이 ${#all_strong[@]}개 있어요 (파일 경로와 걸린 규칙만 적어요)" "${#all_strong[@]} suspected web shell file(s) (path and rule only)")"
		for h in "${all_strong[@]}"; do
			[ "$shown" -ge "$MAX_LIST" ] && break
			detail "$h"; shown=$((shown + 1))
		done
	fi
	if [ ${#weak[@]} -gt 0 ]; then
		add high P01 "$(t "한번 살펴볼 파일이 ${#weak[@]}개 있어요 (약한 표시라 정상 파일일 수도 있어요)" "${#weak[@]} file(s) worth a look (weak signs, may be normal)")"
		for h in "${weak[@]}"; do
			[ "$shown" -ge "$MAX_LIST" ] && break
			detail "$h"; shown=$((shown + 1))
		done
	fi
	if [ ${#all_strong[@]} -eq 0 ] && [ ${#weak[@]} -eq 0 ]; then
		add pass P01 "$(t "웹쉘로 의심되는 파일을 못 찾았어요" "No suspected web shell found")"
	fi
	if [ "$IS_ROOT" != "1" ]; then
		add unk P01 "$(t "일반 사용자라 읽을 수 없는 폴더는 건너뛰었어요. root 로 다시 돌리면 더 봐요" "Folders you cannot read were skipped. Run as root to see more")"
	fi
	return 0
}

# =====================================================================
# L01 L02 L09 : SSH
# =====================================================================
SSH_STOP=0
ssh_cfg_lines() {
	local f=$1 line key rest g
	[ -r "$f" ] || return 0
	while IFS= read -r line || [ -n "$line" ]; do
		[ "$SSH_STOP" = "1" ] && return 0
		line=${line%$'\r'}
		line="${line#"${line%%[![:space:]]*}"}"
		case "$line" in ''|'#'*) continue ;; esac
		key=${line%%[[:space:]=]*}
		rest=${line#"$key"}
		rest="${rest#"${rest%%[![:space:]=]*}"}"
		key=$(printf '%s' "$key" | tr 'A-Z' 'a-z')
		case "$key" in
			match) SSH_STOP=1; return 0 ;;
			include)
				for g in $rest; do
					case "$g" in /*) ;; *) g="/etc/ssh/$g" ;; esac
					local inc
					for inc in $g; do ssh_cfg_lines "$inc"; done
				done
				;;
			*) printf '%s %s\n' "$key" "$rest" ;;
		esac
	done <"$f"
}

SSH_HAS=0
SSH_PW=""
SSH_ROOT=""
check_ssh() {
	step "SSH"
	local sshd=""
	if has sshd; then sshd=$(command -v sshd); elif [ -x /usr/sbin/sshd ]; then sshd=/usr/sbin/sshd; fi
	if [ -z "$sshd" ]; then
		add pass L01 "$(t "SSH 서버가 안 깔려 있어요" "No SSH server installed")"
		add pass L02 "$(t "SSH 서버가 안 깔려 있어요" "No SSH server installed")"
		return
	fi
	SSH_HAS=1
	local cfg="" how
	if [ "$IS_ROOT" = "1" ]; then
		cfg=$("$sshd" -T 2>/dev/null | tr 'A-Z' 'a-z')
	fi
	if [ -n "$cfg" ]; then
		how="sshd -T"
	else
		if [ ! -r /etc/ssh/sshd_config ]; then
			add unk L01 "$(t "sshd_config 를 읽을 수 없어요. root 로 다시 돌리면 더 봐요" "Cannot read sshd_config. Run as root to see more")"
			add unk L02 "$(t "sshd_config 를 읽을 수 없어요" "Cannot read sshd_config")"
			return
		fi
		SSH_STOP=0
		cfg=$(ssh_cfg_lines /etc/ssh/sshd_config | tr 'A-Z' 'a-z')
		how="sshd_config"
	fi
	first() { printf '%s\n' "$cfg" | awk -v k="$1" '$1 == k { $1 = ""; sub(/^ +/, ""); print; exit }'; }
	local root pw kbd pam am
	root=$(first permitrootlogin)
	pw=$(first passwordauthentication)
	kbd=$(first kbdinteractiveauthentication)
	[ -z "$kbd" ] && kbd=$(first challengeresponseauthentication)
	pam=$(first usepam)
	am=$(first authenticationmethods)
	local defnote=""
	if [ -z "$root" ]; then root="prohibit-password"; defnote=" ($(t "설정이 없어 기본값으로 봤어요" "not set, default assumed"))"; fi
	[ -z "$pw" ] && pw="yes"
	[ -z "$kbd" ] && kbd="yes"
	[ -z "$pam" ] && pam="no"

	local pw_on=0
	[ "$pw" = "yes" ] && pw_on=1
	[ "$kbd" = "yes" ] && [ "$pam" = "yes" ] && pw_on=1
	if [ -n "$am" ] && [ "$am" != "any" ]; then
		case "$am" in *password*|*keyboard-interactive*) ;; *) pw_on=0 ;; esac
	fi
	SSH_PW=$pw_on
	SSH_ROOT=$root

	case "$root" in
		yes)
			if [ "$pw_on" = "1" ]; then
				add crit L01 "$(t "SSH 로 root 가 비밀번호로 바로 로그인할 수 있어요" "SSH allows root to log in with a password") [$how]"
			else
				add high L01 "$(t "SSH root 로그인이 켜져 있어요 (PermitRootLogin yes)" "SSH root login is allowed (PermitRootLogin yes)") [$how]"
			fi
			;;
		*)
			add pass L01 "$(t "SSH root 로그인 설정" "SSH root login setting"): $root$defnote [$how]"
			;;
	esac
	if [ "$pw_on" = "1" ]; then
		add med L02 "$(t "SSH 비밀번호 로그인이 켜져 있어요. 키 로그인만 쓰면 더 안전해요" "SSH password login is on. Key-only login is safer") [$how]"
	else
		add pass L02 "$(t "SSH 비밀번호 로그인이 꺼져 있어요" "SSH password login is off") [$how]"
	fi
}

check_bruteforce() {
	step "$(t "로그인 대입 막기" "brute-force protection")"
	if [ "$SSH_HAS" != "1" ]; then
		add pass L09 "$(t "SSH 서버가 없어요" "No SSH server")"
		return
	fi
	local found="" s
	for s in fail2ban crowdsec sshguard denyhosts; do
		if has systemctl && systemctl is-active --quiet "$s" 2>/dev/null; then found="$found $s"; continue; fi
		if has pgrep; then
			case "$s" in
				fail2ban) pgrep -x fail2ban-server >/dev/null 2>&1 && found="$found $s" ;;
				*) pgrep -x "$s" >/dev/null 2>&1 && found="$found $s" ;;
			esac
		fi
	done
	if [ -n "$found" ]; then
		add pass L09 "$(t "로그인 대입 막기가 돌고 있어요" "Brute-force protection is running"):$found"
	elif [ "$SSH_PW" = "1" ]; then
		add med L09 "$(t "비밀번호 로그인이 켜져 있는데 fail2ban 같은 대입 막기가 없어요" "Password login is on but no brute-force protection such as fail2ban")"
	else
		add low L09 "$(t "fail2ban 같은 대입 막기가 없어요 (비밀번호 로그인은 꺼져 있어요)" "No brute-force protection such as fail2ban (password login is off)")"
	fi
}

# =====================================================================
# L03 : 방화벽 / firewall
# =====================================================================
check_firewall() {
	step "$(t "방화벽" "firewall")"
	local ok=""
	if has systemctl && systemctl is-active --quiet firewalld 2>/dev/null; then ok="firewalld"; fi
	if [ -z "$ok" ] && has ufw; then
		if [ "$IS_ROOT" = "1" ]; then
			ufw status 2>/dev/null | grep -qi '^Status: active' && ok="ufw"
		elif [ -r /etc/ufw/ufw.conf ] && grep -qi '^[[:space:]]*ENABLED=yes' /etc/ufw/ufw.conf; then
			ok="ufw"
		fi
	fi
	if [ -z "$ok" ] && [ "$IS_ROOT" = "1" ] && has nft; then
		nft list ruleset 2>/dev/null | awk '
			/hook input/ { inch = 1; if ($0 ~ /policy drop/) drop = 1; next }
			inch && /^[ \t]*}/ { inch = 0; next }
			inch && NF > 0 { r++ }
			END { exit (drop || r > 0) ? 0 : 1 }' && ok="nftables"
	fi
	if [ -z "$ok" ] && [ "$IS_ROOT" = "1" ] && has iptables && ! has nft; then
		local s
		s=$(iptables -S INPUT 2>/dev/null)
		if printf '%s\n' "$s" | grep -q '^-P INPUT DROP' || printf '%s\n' "$s" | grep -q '^-A INPUT'; then ok="iptables"; fi
	fi
	if [ -n "$ok" ]; then
		add pass L03 "$(t "방화벽이 켜져 있어요" "Firewall is on"): $ok"
	elif [ "$IS_ROOT" = "1" ]; then
		add high L03 "$(t "켜진 방화벽이나 들어오는 길 규칙이 없어요 (클라우드 보안 그룹은 여기서 못 봐요)" "No active firewall or inbound rules found (cloud security groups are not visible here)")"
	else
		add unk L03 "$(t "일반 사용자라 방화벽 규칙을 다 못 봤어요. root 로 다시 돌리면 더 봐요" "Cannot read all firewall rules as a normal user. Run as root to see more")"
	fi
}

# =====================================================================
# L04 L05 : 업데이트 / updates
# =====================================================================
check_updates() {
	step "$(t "보안 업데이트 (받아 둔 목록 기준)" "security updates (cached lists)")"
	if has apt-get; then
		local out total sec ts listdate=""
		out=$(apt-get -s -o Debug::NoLocking=1 dist-upgrade 2>/dev/null)
		if [ -z "$out" ]; then
			add unk L04 "$(t "apt 로 업데이트를 확인하지 못했어요" "Could not check updates with apt")"
		else
			total=$(printf '%s\n' "$out" | grep -c '^Inst ')
			sec=$(printf '%s\n' "$out" | grep '^Inst ' | grep -ci 'security')
			if [ -d /var/lib/apt/lists ]; then
				ts=$(find /var/lib/apt/lists -maxdepth 1 -type f -name '*Release' -printf '%T@\n' 2>/dev/null | sort -n | tail -n 1)
				ts=${ts%.*}
				[ -n "$ts" ] && listdate=$(date -d "@$ts" +%Y-%m-%d 2>/dev/null)
			fi
			local note
			note="$(t "패키지 목록 기준일" "package list date") ${listdate:-?} · $(t "목록을 새로 받지 않았어요" "lists were not refreshed")"
			if [ "$sec" -gt 0 ]; then
				add high L04 "$(t "밀린 보안 업데이트가 ${sec}개 있어요 (전체 ${total}개)" "${sec} pending security update(s) (${total} total)") · $note"
			elif [ "$total" -gt 0 ]; then
				add low L04 "$(t "보안 외 업데이트가 ${total}개 있어요" "${total} non-security update(s)") · $note"
			else
				add pass L04 "$(t "밀린 업데이트가 없어요" "No pending updates") · $note"
			fi
		fi
	elif has dnf || has yum; then
		local pm out rc sec total
		if has dnf; then pm=dnf; else pm=yum; fi
		out=$("$pm" -C -q check-update 2>/dev/null); rc=$?
		if [ "$rc" != "0" ] && [ "$rc" != "100" ]; then
			add unk L04 "$(t "$pm 캐시가 없어 확인하지 못했어요 (root 로 돌리거나 캐시가 있어야 해요)" "No $pm cache to check (run as root or keep a cache)")"
		else
			total=$(printf '%s\n' "$out" | awk 'NF == 3 && $2 ~ /[0-9]/ { n++ } END { print n + 0 }')
			sec=$("$pm" -C -q updateinfo list --security 2>/dev/null | awk 'NF >= 3 && tolower($0) ~ /sec/ { n++ } END { print n + 0 }')
			local note
			note="$(t "받아 둔 캐시 기준 · 새로 받지 않았어요" "based on cached metadata · not refreshed")"
			if [ "$sec" -gt 0 ]; then
				add high L04 "$(t "밀린 보안 업데이트가 ${sec}개 있어요 (전체 ${total}개)" "${sec} pending security update(s) (${total} total)") · $note"
			elif [ "$total" -gt 0 ]; then
				add low L04 "$(t "업데이트가 ${total}개 있어요 (보안 표시 없음)" "${total} update(s) (none marked security)") · $note"
			else
				add pass L04 "$(t "밀린 업데이트가 없어요" "No pending updates") · $note"
			fi
		fi
	else
		add unk L04 "$(t "apt·dnf·yum 이 없어 확인하지 못했어요" "No apt, dnf or yum found")"
	fi

	step "$(t "재부팅 필요" "reboot needed")"
	local running newest k
	running=$(uname -r)
	if [ -f /var/run/reboot-required ] || [ -f /run/reboot-required ]; then
		add med L05 "$(t "업데이트 뒤 재부팅이 필요해요 (reboot-required 표시 있음)" "A reboot is required after updates (reboot-required flag)")"
		return
	fi
	if [ -d /lib/modules ]; then
		newest=""
		for k in /lib/modules/*; do
			[ -d "$k" ] || continue
			k=$(basename "$k")
			[ -e "/lib/modules/$k/modules.dep" ] || [ -e "/boot/vmlinuz-$k" ] || [ -e "/lib/modules/$k/vmlinuz" ] || continue
			if [ -z "$newest" ] || ver_lt "$newest" "$k"; then newest=$k; fi
		done
		if [ -z "$newest" ]; then
			add unk L05 "$(t "깔린 커널 목록을 못 읽었어요" "Could not read installed kernels")"
		elif [ "$newest" != "$running" ] && ver_lt "$running" "$newest"; then
			add med L05 "$(t "새 커널 ${newest} 이 깔렸는데 아직 ${running} 으로 돌고 있어요. 재부팅이 필요해요" "New kernel ${newest} is installed but ${running} is running. Reboot needed")"
		else
			add pass L05 "$(t "지금 커널이 가장 새 버전이에요" "Running the newest installed kernel"): $running"
		fi
	else
		add unk L05 "$(t "커널 목록 폴더가 없어요 (컨테이너일 수 있어요)" "No kernel module folder (may be a container)")"
	fi
}

# =====================================================================
# L06 : 웹 폴더 777 / world-writable in web folders
# =====================================================================
check_world_writable() {
	step "$(t "웹 폴더 쓰기 권한" "web folder permissions")"
	if [ ${#WEB_ROOTS[@]} -eq 0 ]; then
		add unk L06 "$(t "웹 폴더를 못 찾았어요 (--web 으로 알려 주세요)" "No web folder found (use --web)")"
		return
	fi
	local f n=0 list=()
	while IFS= read -r -d '' f; do
		n=$((n + 1))
		[ ${#list[@]} -lt "$MAX_LIST" ] && list+=("$f")
	done < <(find "${WEB_ROOTS[@]}" \( -name .git -o -name node_modules \) -prune -o \( -type f -o -type d \) -perm -0002 -print0 2>/dev/null)
	if [ "$n" -gt 0 ]; then
		add high L06 "$(t "웹 폴더에 아무나 쓸 수 있는 파일·폴더가 ${n}개 있어요" "${n} world-writable file(s)/folder(s) in web folders")"
		for f in "${list[@]}"; do detail "$f"; done
	else
		add pass L06 "$(t "웹 폴더에 아무나 쓸 수 있는 파일·폴더가 없어요" "No world-writable files or folders in web folders")"
	fi
}

# =====================================================================
# L07 : 낯선 SUID / unknown SUID files
# =====================================================================
KNOWN_SUID=" sudo su passwd chsh chfn newgrp gpasswd mount umount pkexec ping ping6 fusermount fusermount3 ssh-keysign dbus-daemon-launch-helper polkit-agent-helper-1 unix_chkpwd pam_timestamp_check at crontab Xorg.wrap snap-confine chage newuidmap newgidmap userhelper staprun usernetctl mount.nfs mount.cifs mount.ecryptfs_private ksu sg suexec chrome-sandbox pppd traceroute6.iputils ntfs-3g umount.nfs exim4 sudoedit doas vmware-user-suid-wrapper ssh-agent grub2-set-bootflag pam_extrausers_chkpwd mtr-packet arping chkpwd cgclassify cgexec lppasswd ubuntu-core-launcher "
check_suid() {
	step "$(t "SUID 파일 (조금 걸려요)" "SUID files (takes a moment)")"
	local f b n=0 bad=() odd=() seen="|"
	while IFS= read -r -d '' f; do
		case "$seen" in *"|$f|"*) continue ;; esac
		seen="$seen$f|"
		b=$(basename "$f")
		case "$f" in
			/tmp/*|/var/tmp/*|/dev/shm/*|/home/*|/var/www/*|/srv/*|/root/*)
				bad+=("$f"); continue ;;
		esac
		case "$f" in
			/bin/*|/sbin/*|/usr/bin/*|/usr/sbin/*|/usr/lib/*|/usr/lib64/*|/usr/libexec/*|/lib/*|/lib64/*|/usr/lib32/*|/opt/google/*|/usr/share/*)
				case "$KNOWN_SUID" in *" $b "*) continue ;; esac
				;;
		esac
		n=$((n + 1))
		[ ${#odd[@]} -lt "$MAX_LIST" ] && odd+=("$f")
	done < <(
		find / -xdev \( -path /proc -o -path /sys -o -path /var/lib/docker -o -path /var/lib/containers -o -path /var/lib/lxc -o -path /snap \) -prune -o -type f -perm -4000 -print0 2>/dev/null
		for m in /tmp /var/tmp /dev/shm /home; do
			[ -d "$m" ] && find "$m" -xdev -type f -perm -4000 -print0 2>/dev/null
		done
	)
	if [ ${#bad[@]} -gt 0 ]; then
		add crit L07 "$(t "임시·사용자·웹 폴더에 SUID 파일이 있어요" "SUID files in temp, home or web folders")"
		for f in "${bad[@]}"; do detail "$f"; done
	fi
	if [ "$n" -gt 0 ]; then
		add med L07 "$(t "흔하지 않은 SUID 파일이 ${n}개 있어요. 아는 프로그램인지 확인하세요" "${n} uncommon SUID file(s). Check that you know them")"
		for f in "${odd[@]}"; do detail "$f"; done
	fi
	if [ ${#bad[@]} -eq 0 ] && [ "$n" -eq 0 ]; then
		add pass L07 "$(t "낯선 SUID 파일이 없어요" "No unknown SUID files")"
	fi
	if [ "$IS_ROOT" != "1" ]; then
		add unk L07 "$(t "일반 사용자라 못 본 폴더가 있어요. root 로 다시 돌리면 더 봐요" "Some folders were not readable. Run as root to see more")"
	fi
}

# =====================================================================
# L08 : 바깥에 열린 포트 / exposed ports
# =====================================================================
risky_port() {
	case "$1/$2" in
		tcp/2375) echo "crit|Docker API" ;;
		tcp/9000) echo "high|FastCGI(php-fpm)?" ;;
		tcp/3306) echo "high|MySQL/MariaDB" ;;
		tcp/33060) echo "high|MySQL X" ;;
		tcp/5432) echo "high|PostgreSQL" ;;
		tcp/6379) echo "high|Redis" ;;
		tcp/27017) echo "high|MongoDB" ;;
		tcp/9200|tcp/9300) echo "high|Elasticsearch" ;;
		tcp/11211|udp/11211) echo "high|Memcached" ;;
		tcp/5984) echo "high|CouchDB" ;;
		tcp/1433) echo "high|MS SQL" ;;
		tcp/1521) echo "high|Oracle DB" ;;
		tcp/2379) echo "high|etcd" ;;
		tcp/10250) echo "high|kubelet" ;;
		tcp/5900|tcp/5901) echo "high|VNC" ;;
		tcp/23) echo "high|Telnet" ;;
		tcp/445|tcp/139) echo "high|SMB" ;;
		tcp/21) echo "med|FTP" ;;
		tcp/111|udp/111) echo "med|rpcbind" ;;
		tcp/8086) echo "med|InfluxDB" ;;
		tcp/15672) echo "med|RabbitMQ" ;;
		tcp/4369) echo "med|Erlang epmd" ;;
		tcp/3389) echo "med|RDP" ;;
		*) echo "" ;;
	esac
}

check_ports() {
	step "$(t "열린 포트" "listening ports")"
	local raw opt="tuln"
	[ "$IS_ROOT" = "1" ] && opt="tulnp"
	if has ss; then
		raw=$(ss -"$opt" 2>/dev/null | awk 'NR > 1')
	elif has netstat; then
		raw=$(netstat -"$opt" 2>/dev/null | awk '$1 ~ /^(tcp|udp)/ { p = ""; if ($NF ~ /\//) { p = $NF; sub(/^[0-9]+\//, "", p); p = "users:((\"" p "\"" } print $1, "X", 0, 0, $4, $5, p }')
	else
		add unk L08 "$(t "ss·netstat 이 없어 포트를 못 봤어요" "No ss or netstat to list ports")"
		return
	fi
	local parsed
	parsed=$(printf '%s\n' "$raw" | awk '
		NF >= 5 {
			proto = $1; sub(/6$/, "", proto)
			if (proto != "tcp" && proto != "udp") next
			loc = $5
			port = loc; sub(/.*:/, "", port)
			addr = loc; sub(/:[^:]*$/, "", addr)
			gsub(/[\[\]]/, "", addr); sub(/%.*/, "", addr)
			scope = "pub"
			if (addr == "*" || addr == "0.0.0.0" || addr == "::" || addr == "") scope = "all"
			else if (addr ~ /^127\./ || addr == "::1" || addr == "localhost" || addr ~ /^::ffff:127\./) scope = "local"
			else if (addr ~ /^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.|169\.254\.|fe80|fd|fc)/) scope = "lan"
			proc = ""
			if (match($0, /users:\(\("[^"]+"/)) { proc = substr($0, RSTART + 9, RLENGTH - 10) }
			if (port !~ /^[0-9]+$/) next
			print proto, port, scope, proc
		}' | sort -u -k1,1 -k2,2n -k3,3)

	local proto port scope proc r sev name exposed=() risky=0 lan=()
	declare -A shown=()
	while read -r proto port scope proc; do
		[ -n "$port" ] || continue
		[ "$scope" = "local" ] && continue
		local key="$proto/$port/$scope"
		[ -n "${shown[$key]:-}" ] && continue
		shown[$key]=1
		local where
		case "$scope" in
			all) where=$(t "모든 주소" "all addresses") ;;
			pub) where=$(t "특정 공인 주소" "a specific public address") ;;
			lan) where=$(t "내부망 주소" "a private network address") ;;
		esac
		if [ "$scope" = "lan" ]; then
			lan+=("$proto $port${proc:+ ($proc)} · $where")
			continue
		fi
		exposed+=("$proto $port${proc:+ ($proc)} · $where")
		r=$(risky_port "$proto" "$port")
		[ -n "$r" ] || continue
		sev=${r%%|*}; name=${r#*|}
		if [ "$port" = "9000" ]; then
			case "$proc" in php*) sev=crit; name="FastCGI(php-fpm)" ;; "") ;; *) continue ;; esac
		fi
		risky=$((risky + 1))
		add "$sev" L08 "$name ($proto $port) $(t "포트가 ${where}에서 열려 있어요. 방화벽으로 막혀 있지 않다면 바깥에서 들어올 수 있어요" "is listening on ${where}. Reachable from outside unless a firewall blocks it")"
	done <<<"$parsed"

	if [ "$risky" -eq 0 ]; then
		add pass L08 "$(t "DB·Redis 같은 포트가 바깥 주소에 열려 있지 않아요" "No database or cache ports on outside addresses")"
	fi
	if [ ${#exposed[@]} -gt 0 ] || [ ${#lan[@]} -gt 0 ]; then
		add low L08 "$(t "바깥에서 닿을 수 있는 주소로 듣는 포트 목록 (바깥 ${#exposed[@]} · 내부망 ${#lan[@]})" "Ports listening on reachable addresses (outside ${#exposed[@]} · private ${#lan[@]})")"
		local e
		for e in "${exposed[@]}" "${lan[@]}"; do detail "$e"; done
	fi
	if [ "$IS_ROOT" != "1" ]; then
		add unk L08 "$(t "일반 사용자라 포트를 쓰는 프로그램 이름은 못 봤어요" "Program names are hidden for normal users")"
	fi
}

# =====================================================================
# L10 : 크론 의심 줄 / suspicious cron lines
# =====================================================================
check_cron() {
	step "$(t "크론" "cron")"
	local pipe_dl='(curl|wget|fetch)[^|;]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|da|z|k)?sh([[:space:]]|$)'
	local pipe_b64='base64[[:space:]]+(-d|--decode|-D)[^|;]*\|[[:space:]]*(ba|da|z|k)?sh([[:space:]]|$)'
	local tmp_exec='^[[:space:]]*((nohup|sudo|(ba|da|z|k)?sh)[[:space:]]+)*(/tmp|/var/tmp|/dev/shm)/'
	local tmp_exec2='[;&|][[:space:]]*((nohup|sudo|(ba|da|z|k)?sh)[[:space:]]+)*(/tmp|/var/tmp|/dev/shm)/'
	local files=() f hits=() unread=0 sys
	[ -f /etc/crontab ] && files+=("/etc/crontab|sys")
	for f in /etc/cron.d/*; do [ -f "$f" ] && files+=("$f|sys"); done
	for f in /var/spool/cron/* /var/spool/cron/crontabs/*; do
		[ -f "$f" ] || continue
		if [ -r "$f" ]; then files+=("$f|user"); else unread=1; fi
	done
	[ -d /var/spool/cron ] && [ ! -r /var/spool/cron ] && unread=1
	[ -d /var/spool/cron/crontabs ] && [ ! -r /var/spool/cron/crontabs ] && unread=1

	local ent lineno line cmd rule
	for ent in "${files[@]}"; do
		f=${ent%|*}; sys=${ent##*|}
		[ -r "$f" ] || { unread=1; continue; }
		lineno=0
		while IFS= read -r line || [ -n "$line" ]; do
			lineno=$((lineno + 1))
			line=${line%$'\r'}
			line="${line#"${line%%[![:space:]]*}"}"
			case "$line" in ''|'#'*) continue ;; esac
			[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && continue
			if [[ "$line" =~ ^@ ]]; then
				if [ "$sys" = "sys" ]; then cmd=$(printf '%s' "$line" | awk '{ $1 = ""; $2 = ""; sub(/^ +/, ""); print }')
				else cmd=$(printf '%s' "$line" | awk '{ $1 = ""; sub(/^ +/, ""); print }'); fi
			else
				if [ "$sys" = "sys" ]; then cmd=$(printf '%s' "$line" | awk '{ for (i = 1; i <= 6; i++) $i = ""; sub(/^ +/, ""); print }')
				else cmd=$(printf '%s' "$line" | awk '{ for (i = 1; i <= 5; i++) $i = ""; sub(/^ +/, ""); print }'); fi
			fi
			rule=""
			printf '%s' "$cmd" | grep -qiE -e "$pipe_dl" && rule="download_pipe_shell"
			[ -z "$rule" ] && printf '%s' "$cmd" | grep -qiE -e "$pipe_b64" && rule="base64_pipe_shell"
			[ -z "$rule" ] && printf '%s' "$cmd" | grep -qE -e "$tmp_exec" -e "$tmp_exec2" && rule="run_from_tmp"
			[ -n "$rule" ] && hits+=("$f:$lineno ($rule)")
		done <"$f"
	done
	if has crontab; then
		local own
		own=$(crontab -l 2>/dev/null)
		if [ -n "$own" ]; then
			lineno=0
			while IFS= read -r line; do
				lineno=$((lineno + 1))
				line="${line#"${line%%[![:space:]]*}"}"
				case "$line" in ''|'#'*) continue ;; esac
				[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && continue
				if [[ "$line" =~ ^@ ]]; then
					cmd=$(printf '%s' "$line" | awk '{ $1 = ""; sub(/^ +/, ""); print }')
				else
					cmd=$(printf '%s' "$line" | awk '{ for (i = 1; i <= 5; i++) $i = ""; sub(/^ +/, ""); print }')
				fi
				rule=""
				printf '%s' "$cmd" | grep -qiE -e "$pipe_dl" && rule="download_pipe_shell"
				[ -z "$rule" ] && printf '%s' "$cmd" | grep -qiE -e "$pipe_b64" && rule="base64_pipe_shell"
				[ -z "$rule" ] && printf '%s' "$cmd" | grep -qE -e "$tmp_exec" -e "$tmp_exec2" && rule="run_from_tmp"
				[ -n "$rule" ] && hits+=("crontab -l ($(id -un)):$lineno ($rule)")
			done <<<"$own"
		fi
	fi
	for f in /etc/cron.hourly/* /etc/cron.daily/* /etc/cron.weekly/* /etc/cron.monthly/*; do
		[ -f "$f" ] && [ -r "$f" ] || continue
		grep -qiE -e "$pipe_dl" -e "$pipe_b64" -- "$f" 2>/dev/null && hits+=("$f (download_pipe_shell)")
	done
	if [ ${#hits[@]} -gt 0 ]; then
		add crit L10 "$(t "크론에 의심스러운 줄이 ${#hits[@]}개 있어요 (파일과 줄 번호만 적어요)" "${#hits[@]} suspicious cron line(s) (file and line number only)")"
		for f in "${hits[@]}"; do detail "$f"; done
	else
		add pass L10 "$(t "크론에 의심스러운 줄이 없어요" "No suspicious cron lines")"
	fi
	if [ "$unread" = "1" ]; then
		add unk L10 "$(t "다른 사용자 크론은 못 읽었어요. root 로 다시 돌리면 더 봐요" "Could not read other users' crontabs. Run as root to see more")"
	fi
}

# =====================================================================
# L11 : 임시 폴더의 실행 파일 / executables in temp folders
# =====================================================================
check_tmp_exec() {
	step "$(t "임시 폴더 실행 파일" "executables in temp folders")"
	local f magic elf=() scripts=() d
	for d in /tmp /var/tmp /dev/shm; do
		[ -d "$d" ] || continue
		while IFS= read -r -d '' f; do
			magic=$(head -c 4 -- "$f" 2>/dev/null | od -An -tx1 2>/dev/null | tr -d ' \n')
			case "$magic" in
				7f454c46) elf+=("$f") ;;
				2321*) scripts+=("$f") ;;
			esac
		done < <(find "$d" -xdev -maxdepth 4 -type f -perm /111 -print0 2>/dev/null)
	done
	local shown=0
	if [ ${#elf[@]} -gt 0 ]; then
		add high L11 "$(t "임시 폴더에 실행 프로그램(ELF)이 ${#elf[@]}개 있어요. 모르는 것이면 살펴보세요" "${#elf[@]} executable program(s) (ELF) in temp folders. Check any you do not know")"
		for f in "${elf[@]}"; do [ "$shown" -ge "$MAX_LIST" ] && break; detail "$f"; shown=$((shown + 1)); done
	fi
	if [ ${#scripts[@]} -gt 0 ]; then
		add low L11 "$(t "임시 폴더에 실행 권한이 있는 스크립트가 ${#scripts[@]}개 있어요" "${#scripts[@]} executable script(s) in temp folders")"
		for f in "${scripts[@]}"; do [ "$shown" -ge "$MAX_LIST" ] && break; detail "$f"; shown=$((shown + 1)); done
	fi
	if [ ${#elf[@]} -eq 0 ] && [ ${#scripts[@]} -eq 0 ]; then
		add pass L11 "$(t "임시 폴더에 실행 파일이 없어요" "No executables in temp folders")"
	fi
}

# =====================================================================
# L12 : sudo NOPASSWD
# =====================================================================
check_sudo() {
	step "sudo"
	if [ ! -e /etc/sudoers ]; then
		add pass L12 "$(t "sudo 설정이 없어요" "No sudo configuration")"
		return
	fi
	if [ ! -r /etc/sudoers ]; then
		add unk L12 "$(t "sudo 설정은 root 만 읽을 수 있어요. root 로 다시 돌리면 더 봐요" "Only root can read sudo settings. Run as root to see more")"
		return
	fi
	local f hits=() ln
	for f in /etc/sudoers /etc/sudoers.d/*; do
		[ -f "$f" ] && [ -r "$f" ] || continue
		while IFS= read -r ln; do
			hits+=("$f:${ln%%:*}")
		done < <(grep -n -E '^[^#]*NOPASSWD' -- "$f" 2>/dev/null)
	done
	if [ ${#hits[@]} -gt 0 ]; then
		add med L12 "$(t "비밀번호 없이 sudo 를 쓰는 규칙이 ${#hits[@]}개 있어요 (파일과 줄 번호만 적어요)" "${#hits[@]} sudo rule(s) without password (file and line only)")"
		for f in "${hits[@]}"; do detail "$f"; done
	else
		add pass L12 "$(t "비밀번호 없는 sudo 규칙이 없어요" "No passwordless sudo rules")"
	fi
}

# =====================================================================
# 실행 / run
# =====================================================================
if [ ${#WEB_ROOTS[@]} -gt 0 ]; then
	say "$(t "웹 폴더" "Web folders"): ${WEB_ROOTS[*]}"
else
	say "$(t "웹 폴더" "Web folders"): $(t "못 찾음 (--web 으로 알려 주세요)" "none found (use --web)")"
fi
say "------------------------------------------------------------------"

check_php_versions
check_php_ini
check_upload_php
check_webshell
check_ssh
check_firewall
check_updates
check_world_writable
check_suid
check_ports
check_bruteforce
check_cron
check_tmp_exec
check_sudo

say "------------------------------------------------------------------"
say "$(t "요약" "Summary"): $(t "긴급" "Critical") ${CNT[crit]} · $(t "중요" "High") ${CNT[high]} · $(t "보통" "Medium") ${CNT[med]} · $(t "참고" "Low") ${CNT[low]} · $(t "통과" "Pass") ${CNT[pass]} · $(t "확인 못 함" "Unknown") ${CNT[unk]}"
if [ "$IS_ROOT" != "1" ]; then
	say "$(t "관리자(root)로 다시 돌리면 더 봐요: sudo bash appdogu-check.sh" "Run again as root to see more: sudo bash appdogu-check.sh")"
fi
say "$(t "이 점검은 아무것도 바꾸지 않았어요." "This check changed nothing.")"

OUT_DIR=$(pwd 2>/dev/null)
if [ -z "$OUT_DIR" ] || [ ! -w "$OUT_DIR" ]; then OUT_DIR=/tmp; fi
OUT_FILE="$OUT_DIR/appdogu-check-$STAMP.txt"
if printf '%s\n' "${OUT_LINES[@]}" >"$OUT_FILE" 2>/dev/null; then
	printf '%s: %s\n' "$(t "결과 파일" "Result file")" "$OUT_FILE"
else
	printf '%s\n' "$(t "결과 파일을 쓰지 못했어요 (화면 결과만 있어요)" "Could not write the result file (screen only)")" >&2
fi
exit 0
