Repository navigation
Expand file tree
/
Copy pathphp2shell-mitigation.sh
More file actions
765 lines (711 loc) · 34.4 KB
/
Copy pathphp2shell-mitigation.sh
File metadata and controls
765 lines (711 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
#!/usr/bin/env bash
#
# php2shell-mitigation.sh
#
# Interim mitigation for the PHP "php2shell" vulnerabilities
# (CVE-2026-109618 / CVE-2026-109619): session.upload_progress.enabled = Off
#
# * finds every PHP installation on the host (CLI, FPM, mod_php, LiteSpeed,
# cPanel / Plesk / CloudLinux / Remi, Docker-style and source builds)
# * backs up every file before touching it (central backup dir + manifest)
# * prefers a drop-in file in the conf.d / php.d scan directory, otherwise
# edits php.ini in place inside marker lines, or creates a minimal php.ini
# when none exists (PHP's built-in default for the directive is On)
# * optionally locks the directive in every PHP-FPM pool (php_admin_flag),
# so a .user.ini / .htaccess / ini_set() cannot re-enable it
# * reloads php-fpm / Apache / LiteSpeed gracefully, after a config test
# * REVERT=true removes everything the script added and restores the lines
# it commented out; the raw backups can be restored instead if preferred
#
# Designed for unattended runs (CoreUpdate etc.): edit the SETTINGS block and
# run as root, no arguments needed. Flags override the SETTINGS block:
# --apply --revert --dry-run --no-reload --no-pools --restore-backup
#
# Exit codes: 0 = done, 1 = fatal (not root, bad flag),
# 2 = done with warnings (a target still reports On, a reload or
# an FPM config test failed, overrides found)
#
# THIS IS A STOPGAP, NOT A FIX. It is reported to close only one of the two
# suspected code paths. Patch PHP as soon as fixed packages are available.
#
set -u
set -o pipefail
########################### SETTINGS - edit here ##############################
REVERT=false # false = apply the mitigation, true = remove it
DRY_RUN=false # true = report only, change nothing
RELOAD_SERVICES=true # reload php-fpm / apache / litespeed after changes
HARDEN_FPM_POOLS=true # add php_admin_flag[...] = off to every FPM pool
SCAN_OVERRIDES=true # report .user.ini / .htaccess / vhost overrides
RESTORE_FROM_BACKUP=false # revert: copy raw backups back instead of removing markers
STATE_DIR=/var/lib/php2shell-mitigation # backups + manifest
EXTRA_INI_FILES=() # extra php.ini paths for exotic installs, e.g. (/srv/php/php.ini)
EXTRA_SCAN_DIRS=() # extra scan dirs (conf.d) for exotic installs
###############################################################################
readonly SCRIPT_NAME="php2shell-mitigation"
readonly DIRECTIVE="session.upload_progress.enabled"
readonly DROPIN_NAME="zz-${SCRIPT_NAME}.ini"
readonly MARK_BEGIN="; >>> ${SCRIPT_NAME} BEGIN (CVE-2026-109618 / CVE-2026-109619) - managed by ${SCRIPT_NAME}, do not edit"
readonly MARK_END="; <<< ${SCRIPT_NAME} END"
readonly MARK_BEGIN_RE="${SCRIPT_NAME} BEGIN"
readonly MARK_END_RE="${SCRIPT_NAME} END"
readonly DISABLED_PREFIX=";${SCRIPT_NAME}-disabled: "
readonly INI_LINE="${DIRECTIVE} = Off"
readonly NO_EOL_FLAG="; ${SCRIPT_NAME}: original file had no trailing newline"
readonly POOL_LINE="php_admin_flag[${DIRECTIVE}] = off"
RUN_TS="$(date +%Y%m%d-%H%M%S)"
MANIFEST="${STATE_DIR}/applied.manifest"
WARNINGS=0
CHANGES=0
# ----------------------------------------------------------------------------
# logging
# ----------------------------------------------------------------------------
log() { printf '%s\n' "$*"; }
info() { printf '[INFO] %s\n' "$*"; }
ok() { printf '[OK] %s\n' "$*"; }
warn() { printf '[WARN] %s\n' "$*" >&2; WARNINGS=$((WARNINGS + 1)); }
die() { printf '[FATAL] %s\n' "$*" >&2; exit 1; }
dry() { printf '[DRY] %s\n' "$*"; }
# ----------------------------------------------------------------------------
# args
# ----------------------------------------------------------------------------
usage() {
sed -n '2,32p' "$0" | sed 's/^# \{0,1\}//'
exit 0
}
for arg in "$@"; do
case "$arg" in
--apply) REVERT=false ;;
--revert) REVERT=true ;;
--dry-run) DRY_RUN=true ;;
--no-reload) RELOAD_SERVICES=false ;;
--no-pools) HARDEN_FPM_POOLS=false ;;
--restore-backup) RESTORE_FROM_BACKUP=true ;;
-h|--help) usage ;;
*) die "unknown flag: $arg (use --help)" ;;
esac
done
# normalise booleans typed by hand in the SETTINGS block
norm_bool() { case "$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" in 1|true|yes|on) echo true ;; *) echo false ;; esac; }
REVERT=$(norm_bool "$REVERT"); DRY_RUN=$(norm_bool "$DRY_RUN")
RELOAD_SERVICES=$(norm_bool "$RELOAD_SERVICES"); HARDEN_FPM_POOLS=$(norm_bool "$HARDEN_FPM_POOLS")
SCAN_OVERRIDES=$(norm_bool "$SCAN_OVERRIDES"); RESTORE_FROM_BACKUP=$(norm_bool "$RESTORE_FROM_BACKUP")
# ----------------------------------------------------------------------------
# preflight
# ----------------------------------------------------------------------------
[ "${BASH_VERSINFO[0]}" -ge 4 ] || die "bash 4+ required"
if [ "$DRY_RUN" = false ] && [ "$(id -u)" -ne 0 ]; then die "must run as root"; fi
for t in awk sed grep find cp mktemp; do command -v "$t" >/dev/null 2>&1 || die "missing tool: $t"; done
TIMEOUT_CMD=""
command -v timeout >/dev/null 2>&1 && TIMEOUT_CMD="timeout 25"
MODE="APPLY"; [ "$REVERT" = true ] && MODE="REVERT"
BACKUP_DIR="${STATE_DIR}/backups/${RUN_TS}-$(printf '%s' "$MODE" | tr '[:upper:]' '[:lower:]')-$$"
if [ "$DRY_RUN" = false ]; then
mkdir -p "$BACKUP_DIR" || die "cannot create $BACKUP_DIR"
chmod 700 "$STATE_DIR" 2>/dev/null || true
fi
log "=============================================================="
log " ${SCRIPT_NAME} - mode: ${MODE}$( [ "$DRY_RUN" = true ] && printf ' (DRY RUN)' )"
log " host: $(hostname 2>/dev/null) date: $(date -u +'%Y-%m-%d %H:%M:%S UTC')"
log "=============================================================="
# ----------------------------------------------------------------------------
# generic helpers
# ----------------------------------------------------------------------------
realpath_f() { readlink -f -- "$1" 2>/dev/null || printf '%s' "$1"; }
# copy a file into the backup tree, print the backup path
backup_file() {
local src="$1" dst
dst="${BACKUP_DIR}${src}"
mkdir -p "$(dirname "$dst")"
cp -pL -- "$src" "$dst" || { warn "backup failed for $src"; return 1; }
printf '%s' "$dst"
}
record() { # TYPE path backup
[ "$DRY_RUN" = true ] && return 0
printf '%s|%s|%s|%s\n' "$1" "$2" "${3:-}" "$RUN_TS" >> "$MANIFEST"
}
# replace a file's content with the content of a temp file, preserving inode,
# permissions, owner and SELinux context (truncate + write)
replace_content() { # tmp target
cat -- "$1" > "$2" && rm -f -- "$1"
}
has_marker() { grep -q -- "$MARK_BEGIN_RE" "$1" 2>/dev/null; }
# after a revert: drop the one blank line apply had added before the block,
# and with no_eol=1 the final newline awk added to a file that had none
strip_trailing_blank() { # file no_eol
local f="$1" tail2
command -v truncate >/dev/null 2>&1 || return 0
if [ -s "$f" ]; then
tail2=$(tail -c 2 -- "$f" | od -An -c | tr -d ' \n')
[ "$tail2" = '\n\n' ] && truncate -s -1 -- "$f"
fi
if [ "${2:-0}" = 1 ] && [ -s "$f" ] && [ -z "$(tail -c 1 -- "$f")" ]; then truncate -s -1 -- "$f"; fi
}
# prints 1 when the file does not end with a newline
no_trailing_newline() { if [ -s "$1" ] && [ -n "$(tail -c 1 -- "$1")" ]; then echo 1; else echo 0; fi; }
# ---- php.ini in-place apply -------------------------------------------------
ini_apply_inplace() { # file
local f="$1" tmp bak
if has_marker "$f"; then ok "already applied: $f"; return 0; fi
if [ "$DRY_RUN" = true ]; then dry "would edit in place: $f (comment out existing '${DIRECTIVE}' lines, append marker block)"; return 0; fi
bak=$(backup_file "$f") || return 1
tmp=$(mktemp) || return 1
awk -v pfx="$DISABLED_PREFIX" -v directive="$DIRECTIVE" -v mb="$MARK_BEGIN" -v me="$MARK_END" -v line="$INI_LINE" -v noeol="$(no_trailing_newline "$f")" -v flag="$NO_EOL_FLAG" '
BEGIN { d = directive; gsub(/\./, "\\.", d); re = "^[[:space:]]*" d "[[:space:]]*=" }
{
if ($0 ~ re) { print pfx $0; next }
print $0
}
END { print ""; print mb; if (noeol == 1) print flag; print line; print me }
' "$f" > "$tmp" || { rm -f "$tmp"; warn "awk failed on $f"; return 1; }
[ -s "$tmp" ] || { rm -f "$tmp"; warn "empty result for $f, aborted"; return 1; }
replace_content "$tmp" "$f" || { warn "write failed on $f"; return 1; }
record MODIFIED "$f" "$bak"
CHANGES=$((CHANGES + 1))
ok "edited in place: $f (backup: $bak)"
}
# ---- php.ini / pool in-place revert ----------------------------------------
ini_revert_inplace() { # file
local f="$1" tmp bak
has_marker "$f" || grep -q -- "^${DISABLED_PREFIX}" "$f" 2>/dev/null || return 0
if [ "$DRY_RUN" = true ]; then dry "would remove marker block and restore commented lines in: $f"; return 0; fi
bak=$(backup_file "$f") || return 1
tmp=$(mktemp) || return 1
local noeol=0; grep -qF -- "$NO_EOL_FLAG" "$f" && noeol=1
awk -v pfx="$DISABLED_PREFIX" -v mbre="$MARK_BEGIN_RE" -v mere="$MARK_END_RE" '
BEGIN { skip = 0; plen = length(pfx) }
index($0, mbre) > 0 { skip = 1; next }
index($0, mere) > 0 { skip = 0; next }
skip == 1 { next }
{ if (substr($0, 1, plen) == pfx) { print substr($0, plen + 1) } else { print $0 } }
' "$f" > "$tmp" || { rm -f "$tmp"; warn "awk failed on $f"; return 1; }
replace_content "$tmp" "$f" || { warn "write failed on $f"; return 1; }
strip_trailing_blank "$f" "$noeol"
record REVERTED "$f" "$bak"
CHANGES=$((CHANGES + 1))
ok "reverted: $f (backup of pre-revert state: $bak)"
}
# ---- drop-in ---------------------------------------------------------------
dropin_apply() { # scan_dir
local d="$1" f="$1/${DROPIN_NAME}"
if [ -f "$f" ] && has_marker "$f"; then ok "already applied: $f"; return 0; fi
if [ "$DRY_RUN" = true ]; then dry "would create drop-in: $f"; return 0; fi
if [ -e "$f" ]; then
local bak; bak=$(backup_file "$f") || return 1
record MODIFIED "$f" "$bak"
fi
{ printf '%s\n' "$MARK_BEGIN"; printf '%s\n' "$INI_LINE"; printf '%s\n' "$MARK_END"; } > "$f" || { warn "cannot write $f"; return 1; }
chmod 644 "$f" 2>/dev/null || true
command -v restorecon >/dev/null 2>&1 && restorecon "$f" 2>/dev/null || true
record DROPIN "$f" ""
CHANGES=$((CHANGES + 1))
ok "drop-in created: $f"
}
dropin_revert() { # file
local f="$1"
[ -f "$f" ] || return 0
if ! has_marker "$f"; then warn "drop-in $f exists but has no marker, left untouched"; return 0; fi
if [ "$DRY_RUN" = true ]; then dry "would delete drop-in: $f"; return 0; fi
local bak; bak=$(backup_file "$f") || true
rm -f -- "$f" && { record REVERTED "$f" "$bak"; CHANGES=$((CHANGES + 1)); ok "drop-in removed: $f"; }
}
# ---- minimal php.ini -------------------------------------------------------
ini_create_minimal() { # file
local f="$1"
if [ "$DRY_RUN" = true ]; then dry "would create minimal php.ini: $f"; return 0; fi
[ -d "$(dirname "$f")" ] || mkdir -p "$(dirname "$f")" || { warn "cannot create $(dirname "$f")"; return 1; }
{
printf '; php.ini created by %s on %s\n' "$SCRIPT_NAME" "$RUN_TS"
printf '; No php.ini existed here: all other settings keep PHP built-in defaults.\n'
printf '%s\n' "$MARK_BEGIN" "$INI_LINE" "$MARK_END"
} > "$f" || { warn "cannot write $f"; return 1; }
chmod 644 "$f" 2>/dev/null || true
command -v restorecon >/dev/null 2>&1 && restorecon "$f" 2>/dev/null || true
record CREATED "$f" ""
CHANGES=$((CHANGES + 1))
ok "minimal php.ini created: $f"
}
ini_remove_created() { # file (revert of a CREATED file)
local f="$1"
[ -f "$f" ] || return 0
if ! grep -q -- "created by ${SCRIPT_NAME}" "$f"; then ini_revert_inplace "$f"; return; fi
# delete only if nothing else was added to the file since
if [ "$(grep -v -e '^;' -e '^[[:space:]]*$' -- "$f" | grep -v -- "^${DIRECTIVE}" | wc -l)" -ne 0 ]; then
warn "$f was created by us but has been modified since: reverting markers only"
ini_revert_inplace "$f"; return
fi
if [ "$DRY_RUN" = true ]; then dry "would delete php.ini we created: $f"; return 0; fi
local bak; bak=$(backup_file "$f") || true
rm -f -- "$f" && { record REVERTED "$f" "$bak"; CHANGES=$((CHANGES + 1)); ok "removed php.ini we had created: $f"; }
}
# ---- FPM pool --------------------------------------------------------------
pool_apply() { # file
local f="$1" tmp bak
if has_marker "$f"; then ok "pool already hardened: $f"; return 0; fi
# does the file contain at least one non-global section?
grep -Eq '^[[:space:]]*\[[^]]+\]' "$f" || return 0
if ! awk '/^[[:space:]]*\[[^]]+\]/ { s=$0; sub(/^[[:space:]]*\[/,"",s); sub(/\].*$/,"",s); if (tolower(s) != "global") found=1 } END { exit found ? 0 : 1 }' "$f"; then
return 0
fi
if [ "$DRY_RUN" = true ]; then dry "would add '${POOL_LINE}' to every pool in: $f"; return 0; fi
bak=$(backup_file "$f") || return 1
tmp=$(mktemp) || return 1
awk -v pfx="$DISABLED_PREFIX" -v mb="$MARK_BEGIN" -v me="$MARK_END" -v line="$POOL_LINE" -v directive="$DIRECTIVE" '
BEGIN { d = directive; gsub(/\./, "\\.", d); ovr = "^[[:space:]]*php_(admin_)?(value|flag)\\[" d "\\]" }
{
if ($0 ~ /^[[:space:]]*\[[^]]+\][[:space:]]*(;.*)?\r?$/) {
s = $0; sub(/^[[:space:]]*\[/, "", s); sub(/\].*$/, "", s)
print $0
if (tolower(s) != "global") { print mb; print line; print me }
next
}
if ($0 ~ ovr) { print pfx $0; next }
print $0
}
' "$f" > "$tmp" || { rm -f "$tmp"; warn "awk failed on $f"; return 1; }
[ -s "$tmp" ] || { rm -f "$tmp"; warn "empty result for $f, aborted"; return 1; }
replace_content "$tmp" "$f" || { warn "write failed on $f"; return 1; }
record POOL "$f" "$bak"
CHANGES=$((CHANGES + 1))
POOLS_TOUCHED+=("$f|$bak")
ok "pool hardened: $f (backup: $bak)"
}
# ----------------------------------------------------------------------------
# discovery
# ----------------------------------------------------------------------------
declare -a CLI_BINS=() FPM_BINS=()
declare -A SEEN_BIN=()
add_bin() { # path kind
local p; p=$(realpath_f "$1")
[ -x "$p" ] && [ -f "$p" ] || return 0
[ -n "${SEEN_BIN[$p]:-}" ] && return 0
SEEN_BIN[$p]=1
if [ "$2" = fpm ]; then FPM_BINS+=("$p"); else CLI_BINS+=("$p"); fi
}
find_php_binaries() {
local d f base
local dirs=(
/usr/bin /usr/sbin /usr/local/bin /usr/local/sbin /bin /sbin
/opt/remi/php*/root/usr/bin /opt/remi/php*/root/usr/sbin
/opt/cpanel/ea-php*/root/usr/bin /opt/cpanel/ea-php*/root/usr/sbin
/opt/plesk/php/*/bin /opt/plesk/php/*/sbin
/opt/alt/php*/usr/bin /opt/alt/php*/usr/sbin
/usr/local/php*/bin /usr/local/php*/sbin /opt/php*/bin /opt/php*/sbin
/usr/local/lsws/lsphp*/bin
)
# binaries from PATH first
local IFS=:; for d in $PATH; do dirs+=("$d"); done; unset IFS
for d in "${dirs[@]}"; do
[ -d "$d" ] || continue
for f in "$d"/php "$d"/php[0-9]* "$d"/php-fpm "$d"/php-fpm[0-9]* "$d"/php-cgi "$d"/php-cgi[0-9]*; do
[ -e "$f" ] || continue
base=$(basename "$f")
case "$base" in
php|php[0-9]|php[0-9][0-9]|php[0-9].[0-9]|php[0-9].[0-9][0-9]) add_bin "$f" cli ;;
php-fpm|php-fpm[0-9]*) add_bin "$f" fpm ;;
php-cgi|php-cgi[0-9]*) : ;; # CGI prints HTML, covered via path scan
*) : ;;
esac
done
done
# running php-fpm masters (Docker, no systemd...) give us extra binaries + conf paths
if command -v ps >/dev/null 2>&1; then
while IFS= read -r line; do
[ -n "$line" ] || continue
FPM_MASTERS+=("$line")
done < <(ps -eo pid=,args= 2>/dev/null | grep -F 'php-fpm: master process' | grep -v grep || true)
else # minimal containers without procps: walk /proc
local p cmd
for p in /proc/[0-9]*; do
cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null) || continue
case "$cmd" in *"php-fpm: master process"*) FPM_MASTERS+=("${p#/proc/} $cmd") ;; esac
done
fi
}
# is a process with this name running? (pgrep, or /proc walk when procps is absent)
proc_running() { # name
if command -v pgrep >/dev/null 2>&1; then pgrep -x "$1" >/dev/null 2>&1; return; fi
local p
for p in /proc/[0-9]*; do [ "$(cat "$p/comm" 2>/dev/null)" = "$1" ] && return 0; done
return 1
}
php_info() { # bin [extra args...] -> stdout of -i
local bin="$1"; shift
$TIMEOUT_CMD "$bin" "$@" -i 2>/dev/null </dev/null || true
}
# targets: ini file + scan dir + label + default dir (where PHP would look)
declare -a T_INI=() T_SCAN=() T_LABEL=() T_DEFDIR=() T_BIN=()
declare -A SEEN_TARGET=()
add_target() { # ini scan label defdir bin
local ini="$1" scan="$2" label="$3" defdir="$4" bin="$5" key
[ "$ini" = "(none)" ] && ini=""
[ "$scan" = "(none)" ] && scan=""
[ -n "$ini" ] && ini=$(realpath_f "$ini")
[ -n "$scan" ] && scan=$(realpath_f "$scan")
[ -n "$scan" ] && [ ! -d "$scan" ] && scan=""
[ -n "$scan" ] && [ -n "$ini" ] && [ ! -f "$ini" ] && ini="" # drop-in will do, missing php.ini is irrelevant
[ -z "$ini" ] && [ -z "$scan" ] && [ -z "$defdir" ] && return 0
key="${ini}|${scan}"; [ -z "$ini" ] && [ -z "$scan" ] && key="defdir:${defdir}"
[ -n "${SEEN_TARGET[$key]:-}" ] && return 0
SEEN_TARGET[$key]=1
T_INI+=("$ini"); T_SCAN+=("$scan"); T_LABEL+=("$label"); T_DEFDIR+=("$defdir"); T_BIN+=("$bin")
}
targets_from_binaries() {
local bin out ini scan defdir sapi
for bin in ${CLI_BINS[@]+"${CLI_BINS[@]}"} ${FPM_BINS[@]+"${FPM_BINS[@]}"}; do
out=$(php_info "$bin")
if [ -z "$out" ]; then warn "could not run '$bin -i' (broken install?), skipped"; continue; fi
ini=$(printf '%s\n' "$out" | sed -n 's/^Loaded Configuration File => //p' | head -1)
scan=$(printf '%s\n' "$out" | sed -n 's/^Scan this dir for additional .ini files => //p' | head -1)
defdir=$(printf '%s\n' "$out" | sed -n 's/^Configuration File (php.ini) Path => //p' | head -1)
sapi=$(printf '%s\n' "$out" | sed -n 's/^Server API => //p' | head -1)
if ! printf '%s\n' "$out" | grep -q "^${DIRECTIVE} => "; then
info "$bin: session extension not loaded for this SAPI (directive absent), nothing to do for it"
continue
fi
add_target "$ini" "$scan" "${sapi:-?} via $bin" "$defdir" "$bin"
done
}
# well-known layouts (covers mod_php dirs that have no binary to query, and
# installs whose binary is not in PATH)
targets_from_known_paths() {
local d s
local -a pairs=(
# "<dir containing php.ini>|<scan dir>"
"/etc/php/*/cli|conf.d" "/etc/php/*/fpm|conf.d" "/etc/php/*/apache2|conf.d" "/etc/php/*/cgi|conf.d"
"/etc/php/*/litespeed|conf.d" "/etc/php/*/embed|conf.d" "/etc/php/*/phpdbg|conf.d" # Debian / Ubuntu
"/etc|php.d" # RHEL / Fedora
"/etc/php|conf.d" # Arch
"/etc/php[0-9]*|conf.d" # Alpine (/etc/php84)
"/etc/php[0-9]*/cli|../conf.d" "/etc/php[0-9]*/fpm|../conf.d" "/etc/php[0-9]*/apache2|../conf.d" # openSUSE
"/etc/opt/remi/php*|php.d" # Remi SCL
"/opt/cpanel/ea-php*/root/etc|php.d" # cPanel EasyApache
"/opt/plesk/php/*/etc|php.d" # Plesk
"/opt/alt/php*/etc|php.d" # CloudLinux alt-php
"/usr/local/lsws/lsphp*/etc|php.d" "/usr/local/lsws/lsphp*/etc/php/*/litespeed|conf.d" # LiteSpeed lsphp
"/usr/local/etc/php|conf.d" # official Docker images
"/usr/local/lib|" "/usr/local/php*/etc|conf.d" "/usr/local/php*/lib|" "/opt/php*/etc|conf.d" "/opt/php*/lib|"
)
local pair pat scanrel
for pair in "${pairs[@]}"; do
pat="${pair%%|*}"; scanrel="${pair#*|}"
for d in $pat; do
[ -d "$d" ] || continue
s=""; [ -n "$scanrel" ] && s="$d/$scanrel"
[ -n "$s" ] && [ ! -d "$s" ] && s=""
# only when something actually exists there (never create php.ini in random dirs)
if [ -f "$d/php.ini" ] || [ -n "$s" ]; then
add_target "$d/php.ini" "$s" "known layout $d" "" ""
fi
done
done
local x
for x in ${EXTRA_INI_FILES[@]+"${EXTRA_INI_FILES[@]}"}; do add_target "$x" "" "extra ini" "$(dirname "$x")" ""; done
for x in ${EXTRA_SCAN_DIRS[@]+"${EXTRA_SCAN_DIRS[@]}"}; do add_target "" "$x" "extra scan dir" "" ""; done
}
# ----------------------------------------------------------------------------
# FPM instances (binary + fpm config + pool files + how to reload)
# ----------------------------------------------------------------------------
declare -a FPM_MASTERS=() # "pid args" lines of running masters
declare -a FI_BIN=() FI_CONF=() FI_SVC=() FI_PID=()
declare -A SEEN_FI=()
declare -a POOLS_TOUCHED=()
declare -A FI_BROKEN=() # index -> 1 when config test failed (do not reload)
add_fpm_instance() { # bin conf svc pid
local key="${1}|${2}"
[ -n "${SEEN_FI[$key]:-}" ] && { # merge service / pid info
local i; for i in "${!FI_BIN[@]}"; do
if [ "${FI_BIN[$i]}|${FI_CONF[$i]}" = "$key" ]; then
[ -z "${FI_SVC[$i]}" ] && FI_SVC[$i]="$3"; [ -z "${FI_PID[$i]}" ] && FI_PID[$i]="$4"
fi
done; return 0; }
SEEN_FI[$key]=1
FI_BIN+=("$1"); FI_CONF+=("$2"); FI_SVC+=("$3"); FI_PID+=("$4")
}
fpm_default_conf() { # bin -> conf path from "php-fpm -t"
local bin="$1" out c
out=$($TIMEOUT_CMD "$bin" -t 2>&1 </dev/null || true)
c=$(printf '%s\n' "$out" | sed -n 's/.*configuration file \(.*\) test is successful.*/\1/p' | head -1)
if [ -z "$c" ]; then
c=$(printf '%s\n' "$out" | sed -n "s/.*failed to open configuration file '\([^']*\)'.*/\1/p" | head -1)
[ -n "$c" ] && [ ! -f "$c" ] && c=""
fi
if [ -z "$c" ]; then
local prefix; prefix=$(dirname "$(dirname "$bin")")
local cand
for cand in "$prefix/etc/php-fpm.conf" /etc/php-fpm.conf; do [ -f "$cand" ] && { c="$cand"; break; }; done
fi
printf '%s' "$c"
}
HAVE_SYSTEMD=false
[ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1 && HAVE_SYSTEMD=true
discover_fpm_instances() {
local bin conf svc exec path y pid args
# 1) systemd services
if [ "$HAVE_SYSTEMD" = true ]; then
while IFS= read -r svc; do
[ -n "$svc" ] || continue
exec=$(systemctl show -p ExecStart -- "$svc" 2>/dev/null)
path=$(printf '%s' "$exec" | sed -n 's/.*path=\([^ ;]*\).*/\1/p' | head -1)
y=$(printf '%s' "$exec" | sed -n 's/.*\(--fpm-config\|-y\)[ =]\([^ ;]*\).*/\2/p' | head -1)
[ -n "$path" ] || continue
bin=$(realpath_f "$path")
[ -x "$bin" ] || continue
add_bin "$bin" fpm
conf="$y"; [ -z "$conf" ] && conf=$(fpm_default_conf "$bin")
add_fpm_instance "$bin" "$conf" "$svc" ""
done < <(systemctl list-units --type=service --all --no-legend --plain 2>/dev/null | awk '{print $1}' | grep -E 'php.*fpm' || true)
fi
# 2) running masters: "php-fpm: master process (/path/php-fpm.conf)"
for args in ${FPM_MASTERS[@]+"${FPM_MASTERS[@]}"}; do
pid=$(printf '%s' "$args" | awk '{print $1}')
conf=$(printf '%s' "$args" | sed -n 's/.*master process (\([^)]*\)).*/\1/p')
bin=$(readlink -f "/proc/$pid/exe" 2>/dev/null || true)
[ -n "$bin" ] && [ -x "$bin" ] || continue
add_bin "$bin" fpm
[ -f "$conf" ] || conf=$(fpm_default_conf "$bin")
add_fpm_instance "$bin" "$conf" "" "$pid"
done
# 3) every other fpm binary found on disk, with its default config
for bin in ${FPM_BINS[@]+"${FPM_BINS[@]}"}; do
conf=$(fpm_default_conf "$bin")
[ -n "$conf" ] || { info "no php-fpm.conf found for $bin, pools skipped"; continue; }
add_fpm_instance "$bin" "$conf" "" ""
done
}
# print the pool files of an fpm config (the conf itself + includes, 3 levels)
fpm_pool_files() { # conf prefix [depth]
local conf="$1" prefix="$2" depth="${3:-0}" inc g
[ -f "$conf" ] || return 0
printf '%s\n' "$conf"
[ "$depth" -ge 3 ] && return 0
while IFS= read -r inc; do
inc="${inc%%;*}"; inc="${inc#"${inc%%[![:space:]]*}"}"; inc="${inc%"${inc##*[![:space:]]}"}"
inc="${inc%\"}"; inc="${inc#\"}"; inc="${inc%\'}"; inc="${inc#\'}"
[ -n "$inc" ] || continue
case "$inc" in /*) : ;; *) inc="$prefix/$inc" ;; esac
for g in $inc; do
[ -f "$g" ] && fpm_pool_files "$g" "$prefix" $((depth + 1))
done
done < <(sed -n 's/^[[:space:]]*include[[:space:]]*=[[:space:]]*//p' "$conf")
}
fpm_test() { # idx -> 0 ok
local bin="${FI_BIN[$1]}" conf="${FI_CONF[$1]}"
$TIMEOUT_CMD "$bin" -y "$conf" -t >/dev/null 2>&1 </dev/null
}
process_fpm_pools() { # apply or revert, per instance
local i f prefix changed_before
for i in "${!FI_BIN[@]}"; do
prefix=$(dirname "$(dirname "${FI_BIN[$i]}")")
[ -f "${FI_CONF[$i]}" ] || { warn "fpm config not found: ${FI_CONF[$i]} (bin ${FI_BIN[$i]})"; continue; }
# pre-existing broken config: do not touch, do not reload
if [ "$DRY_RUN" = false ] && ! fpm_test "$i"; then
warn "FPM config test ALREADY FAILS for ${FI_BIN[$i]} -y ${FI_CONF[$i]}: pools left untouched, no reload"
FI_BROKEN[$i]=1; continue
fi
changed_before=${#POOLS_TOUCHED[@]}
while IFS= read -r f; do
[ -n "$f" ] || continue
if [ "$REVERT" = true ]; then ini_revert_inplace "$f"; else pool_apply "$f"; fi
done < <(fpm_pool_files "${FI_CONF[$i]}" "$prefix" | awk '!seen[$0]++')
if [ "$DRY_RUN" = false ] && ! fpm_test "$i"; then
warn "FPM config test FAILED after editing pools of ${FI_BIN[$i]}: rolling those files back"
local j entry
for ((j = changed_before; j < ${#POOLS_TOUCHED[@]}; j++)); do
entry="${POOLS_TOUCHED[$j]}"; cp -a -- "${entry#*|}" "${entry%%|*}" && info "restored ${entry%%|*}"
done
FI_BROKEN[$i]=1
fpm_test "$i" || warn "config still failing after rollback for ${FI_BIN[$i]}, manual check required"
fi
done
}
# ----------------------------------------------------------------------------
# reload
# ----------------------------------------------------------------------------
apache_ctl() { # -> prints a control command that exists
local c; for c in apache2ctl apachectl httpd apache2; do command -v "$c" >/dev/null 2>&1 && { printf '%s' "$c"; return; }; done
}
reload_everything() {
[ "$RELOAD_SERVICES" = true ] || { info "service reload disabled (RELOAD_SERVICES=false)"; return; }
if [ "$DRY_RUN" = true ]; then dry "would reload php-fpm / apache / litespeed services"; return; fi
[ "$CHANGES" -gt 0 ] || { info "nothing changed, no reload needed"; return; }
local i svc done_svc=""
# --- PHP-FPM
for i in "${!FI_BIN[@]}"; do
[ -n "${FI_BROKEN[$i]:-}" ] && { warn "skipping reload of ${FI_BIN[$i]} (config test failed)"; continue; }
if ! fpm_test "$i"; then warn "config test failed, not reloading ${FI_BIN[$i]}"; continue; fi
svc="${FI_SVC[$i]}"
if [ -n "$svc" ] && [ "$HAVE_SYSTEMD" = true ]; then
if systemctl is-active --quiet -- "$svc"; then
systemctl reload-or-restart -- "$svc" && ok "reloaded $svc" || warn "reload failed: $svc"
else info "$svc not active, nothing to reload"; fi
done_svc="$done_svc $svc"
elif [ -n "${FI_PID[$i]}" ]; then
kill -USR2 "${FI_PID[$i]}" 2>/dev/null && ok "sent SIGUSR2 (graceful reload) to php-fpm master pid ${FI_PID[$i]}" || warn "could not signal pid ${FI_PID[$i]}"
else
info "no running service/master found for ${FI_BIN[$i]}, nothing to reload"
fi
done
# --- Apache (mod_php reads php.ini at startup)
if [ "$HAVE_SYSTEMD" = true ]; then
for svc in apache2 httpd lsws lshttpd; do
systemctl is-active --quiet -- "$svc" 2>/dev/null || continue
case "$svc" in
apache2|httpd)
local ctl; ctl=$(apache_ctl)
if [ -n "$ctl" ] && ! "$ctl" -t >/dev/null 2>&1; then warn "apache config test failed, not reloading $svc"; continue; fi
systemctl reload-or-restart -- "$svc" && ok "reloaded $svc" || warn "reload failed: $svc" ;;
lsws|lshttpd)
systemctl reload-or-restart -- "$svc" && ok "reloaded $svc" || warn "reload failed: $svc" ;;
esac
done
else
local ctl; ctl=$(apache_ctl)
if proc_running apache2 || proc_running httpd; then
if [ -n "$ctl" ]; then
if "$ctl" -t >/dev/null 2>&1; then
"$ctl" -k graceful >/dev/null 2>&1 && ok "apache graceful restart via $ctl" || warn "apache graceful restart failed"
else warn "apache config test failed, not restarting"; fi
else warn "apache is running but no apachectl/httpd control command found, restart it manually"; fi
fi
[ -x /usr/local/lsws/bin/lswsctrl ] && proc_running lshttpd && { /usr/local/lsws/bin/lswsctrl restart >/dev/null 2>&1 && ok "litespeed restarted" || warn "litespeed restart failed"; }
fi
}
# ----------------------------------------------------------------------------
# verification
# ----------------------------------------------------------------------------
effective_value() { # idx -> prints value as seen by PHP for that target
local i="$1" bin="${T_BIN[$1]}" ini="${T_INI[$1]}" scan="${T_SCAN[$1]}" out
if [ -n "$bin" ]; then
out=$(php_info "$bin")
else
bin="${CLI_BINS[0]:-}"; [ -n "$bin" ] || { printf 'n/a (no CLI binary to test with)'; return; }
if [ -n "$ini" ] && [ -f "$ini" ]; then
out=$(PHP_INI_SCAN_DIR="$scan" php_info "$bin" -c "$ini")
else
out=$(PHP_INI_SCAN_DIR="$scan" php_info "$bin" -c /dev/null) # empty php.ini, scan dir only
fi
fi
printf '%s\n' "$out" | sed -n "s/^${DIRECTIVE} => \([^ ]*\) => .*/\1/p" | head -1
}
verify_targets() {
local i v want="Off" bad=0
[ "$REVERT" = true ] && want="On"
log ""
log "---- verification (value as parsed by PHP, pool-level php_admin_flag not included) ----"
for i in "${!T_INI[@]}"; do
v=$(effective_value "$i")
[ -z "$v" ] && v="?"
printf ' %-4s %-60s %s\n' "$v" "${T_INI[$i]:-"(no php.ini)"}${T_SCAN[$i]:+ + $(basename "${T_SCAN[$i]}")/}" "[${T_LABEL[$i]}]"
if [ "$REVERT" = false ]; then case "$v" in Off|\?|n/a*) : ;; *) bad=$((bad + 1)) ;; esac; fi
done
if [ "$REVERT" = false ] && [ "$bad" -gt 0 ] && [ "$DRY_RUN" = false ]; then
warn "$bad target(s) still report ${DIRECTIVE} != Off"
fi
log " mod_php / web SAPI: confirm through HTTP with a one-off script: <?php var_dump(ini_get('${DIRECTIVE}'));"
}
scan_overrides() {
[ "$SCAN_OVERRIDES" = true ] || return 0
log ""
log "---- overrides that could re-enable the directive (report only) ----"
local hits tmo=""
command -v timeout >/dev/null 2>&1 && tmo="timeout 90"
hits=$( $tmo find /var/www /srv /home /usr/share/nginx /usr/local/lsws /opt/bitnami /var/lib/www /usr/local/www /data/www /web \
-xdev -maxdepth 7 \( -name .user.ini -o -name .htaccess \) -type f 2>/dev/null \
| head -5000 | xargs -r grep -l -i 'upload_progress' 2>/dev/null || true )
local vh
vh=$(grep -rIl -i 'upload_progress' /etc/apache2 /etc/httpd /etc/nginx /usr/local/lsws/conf 2>/dev/null | head -50 || true)
if [ -z "$hits" ] && [ -z "$vh" ]; then ok "no .user.ini / .htaccess / vhost mentioning upload_progress found"; return 0; fi
local f
for f in $hits $vh; do
printf ' %s\n' "$f"
grep -n -i 'upload_progress' -- "$f" 2>/dev/null | sed 's/^/ /' | head -5
done
warn "the files above mention upload_progress: check they do not set it back On (FPM pools hardened with php_admin_flag are protected)"
}
# ----------------------------------------------------------------------------
# main
# ----------------------------------------------------------------------------
find_php_binaries
targets_from_binaries
targets_from_known_paths
discover_fpm_instances
if [ "${#T_INI[@]}" -eq 0 ] && [ "${#FI_BIN[@]}" -eq 0 ]; then
info "no PHP installation found on this host, nothing to do"
exit 0
fi
log ""
log "---- PHP installations found ----"
for b in ${CLI_BINS[@]+"${CLI_BINS[@]}"} ${FPM_BINS[@]+"${FPM_BINS[@]}"}; do
printf ' %s (%s)\n' "$b" "$($TIMEOUT_CMD "$b" -v 2>/dev/null </dev/null | head -1 || echo '?')"
done
for i in "${!T_INI[@]}"; do
printf ' target: ini=%s scan=%s [%s]\n' "${T_INI[$i]:-"-"}" "${T_SCAN[$i]:-"-"}" "${T_LABEL[$i]}"
done
for i in "${!FI_BIN[@]}"; do
printf ' fpm: %s conf=%s%s%s\n' "${FI_BIN[$i]}" "${FI_CONF[$i]}" "${FI_SVC[$i]:+ service=${FI_SVC[$i]}}" "${FI_PID[$i]:+ masterpid=${FI_PID[$i]}}"
done
log ""
if [ "$REVERT" = false ]; then
log "---- applying: ${INI_LINE} ----"
for i in "${!T_INI[@]}"; do
ini="${T_INI[$i]}"; scan="${T_SCAN[$i]}"; defdir="${T_DEFDIR[$i]}"
if [ -n "$scan" ]; then
dropin_apply "$scan"
# an explicit On in php.ini is overridden by the drop-in (parsed later), nothing else to do
elif [ -n "$ini" ] && [ -f "$ini" ]; then
ini_apply_inplace "$ini"
elif [ -n "$ini" ]; then
ini_create_minimal "$ini"
elif [ -n "$defdir" ] && [ -d "$defdir" ]; then
ini_create_minimal "$defdir/php.ini"
else
warn "target [${T_LABEL[$i]}] has neither php.ini nor scan dir nor default dir, skipped"
fi
done
if [ "$HARDEN_FPM_POOLS" = true ]; then
log ""; log "---- hardening PHP-FPM pools: ${POOL_LINE} ----"
process_fpm_pools
fi
else
log "---- reverting ----"
# 1) what discovery sees now
for i in "${!T_INI[@]}"; do
ini="${T_INI[$i]}"; scan="${T_SCAN[$i]}"
[ -n "$scan" ] && dropin_revert "$scan/${DROPIN_NAME}"
[ -n "$ini" ] && [ -f "$ini" ] && { if grep -q -- "created by ${SCRIPT_NAME}" "$ini" 2>/dev/null; then ini_remove_created "$ini"; else ini_revert_inplace "$ini"; fi; }
done
process_fpm_pools
# 2) what the manifest remembers (files discovery might miss today)
if [ -f "$MANIFEST" ]; then
MANIFEST_COPY=$(mktemp); cp -- "$MANIFEST" "$MANIFEST_COPY"
while IFS='|' read -r type path bak ts; do
[ -f "$path" ] || continue
case "$type" in
DROPIN) dropin_revert "$path" ;;
CREATED) ini_remove_created "$path" ;;
MODIFIED|POOL)
if [ "$RESTORE_FROM_BACKUP" = true ] && [ -f "$bak" ]; then
if [ "$DRY_RUN" = true ]; then dry "would restore $path from $bak"; else cp -a -- "$bak" "$path" && { CHANGES=$((CHANGES + 1)); ok "restored $path from backup $bak"; }; fi
else
ini_revert_inplace "$path"
fi ;;
esac
done < "$MANIFEST_COPY"
rm -f -- "$MANIFEST_COPY"
if [ "$DRY_RUN" = false ]; then mv -f -- "$MANIFEST" "${STATE_DIR}/reverted-${RUN_TS}.manifest"; fi
else
info "no manifest at $MANIFEST (never applied here, or already reverted): marker-based revert only"
fi
fi
log ""
log "---- reload ----"
reload_everything
verify_targets
[ "$REVERT" = false ] && scan_overrides
log ""
log "---- summary ----"
log " mode: $MODE changes: $CHANGES warnings: $WARNINGS"
[ "$DRY_RUN" = false ] && [ "$REVERT" = false ] && log " backups: $BACKUP_DIR manifest: $MANIFEST"
[ "$REVERT" = false ] && log " REMINDER: this is a stopgap. Patch PHP (8.2+ fixed releases) and restart every SAPI."
[ "$WARNINGS" -gt 0 ] && exit 2
exit 0