-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapt-patch.sh
More file actions
462 lines (430 loc) · 24.6 KB
/
Copy pathapt-patch.sh
File metadata and controls
462 lines (430 loc) · 24.6 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
#!/usr/bin/env bash
#
# apt-patch.sh — remediate the "EOL Debian/Ubuntu without security patches" finding.
# ---------------------------------------------------------------------------
# Repoints APT sources to the vendor archive (archive.debian.org /
# old-releases.ubuntu.com), installs the last available patches for the running
# release, and collects audit evidence. Idempotent and production-safe.
#
# Supported (auto-detected from /etc/os-release):
# * Debian -> archive.debian.org (security suite <codename>/updates for <=10, <codename>-security for >=11)
# * Ubuntu -> old-releases.ubuntu.com
# * Debian/Ubuntu derivatives (via ID_LIKE) are allowed for patch with a warning.
# Init system (systemd vs sysvinit) is auto-detected via /proc/1/comm.
#
# Commands:
# ./apt-patch.sh diagnose # read-only overview (safe for an SSH loop)
# ./apt-patch.sh migrate-plan # read-only migration-assessment report
# ./apt-patch.sh patch [--yes] [--dist-upgrade] [--with-thirdparty] [--trust-archive] [--force]
# # --trust-archive: accept the EOL archive's expired signing keys (required
# # for archive.debian.org, whose release keys expire by policy)
# # --force: proceed even if preflight flags the host as a rebuild candidate
# ./apt-patch.sh cleanup-kernels # apt-get autoremove old kernels, with preview
# ./apt-patch.sh verify [URL] [--reset-failed] # post-reboot validation (+ optional portal test)
# ./apt-patch.sh bundle # tar.gz the evidence directory for the ticket
#
# WARNING: an EOL release receives NO new vendor patches. This installs every
# patch that existed up to EOL; vulnerabilities disclosed afterwards are not
# fixable by patching. The durable fix is a dist-upgrade to a supported release
# or migration. Debian bridge: Freexian ELTS. See README.
# ---------------------------------------------------------------------------
set -euo pipefail
SOURCES_MAIN="/etc/apt/sources.list"
SOURCES_D="/etc/apt/sources.list.d"
EVID_ROOT="/root/apt-patch-evidence"
KEEP_KERNELS=2
APT_OPTS=(-o "Acquire::Check-Valid-Until=false")
c_blue="\033[1;34m"; c_grn="\033[1;32m"; c_red="\033[1;31m"; c_yel="\033[1;33m"; c_off="\033[0m"
info(){ echo -e "${c_blue}[*]${c_off} $*"; }
ok(){ echo -e "${c_grn}[OK]${c_off} $*"; }
warn(){ echo -e "${c_yel}[!]${c_off} $*"; }
die(){ echo -e "${c_red}[X]${c_off} $*" >&2; exit 1; }
confirm(){ local a; read -r -p "$(echo -e "${c_yel}[?]${c_off} $1 [y/N] ")" a; [[ "$a" =~ ^[yY] ]]; }
need_root(){ [[ "$(id -u)" -eq 0 ]] || die "Run as root."; }
reachable(){ # $1 url -> 0 if fetchable
if command -v curl >/dev/null 2>&1; then curl -sfL -o /dev/null "$1"
elif command -v wget >/dev/null 2>&1; then wget -q -O /dev/null "$1"
else die "Neither curl nor wget available."; fi
}
# ---- init abstraction -----------------------------------------------------
detect_init(){ case "$(cat /proc/1/comm 2>/dev/null || true)" in systemd) INIT=systemd;; *) INIT=sysv;; esac; }
svc_active(){ # $1 service -> echo active|inactive
if [[ "$INIT" == systemd ]]; then systemctl is-active "$1" 2>/dev/null || echo inactive
else service "$1" status >/dev/null 2>&1 && echo active || echo inactive; fi
}
sys_state(){ [[ "$INIT" == systemd ]] && (systemctl is-system-running 2>/dev/null || true) || echo "sysvinit (no aggregate state)"; }
failed_units(){ [[ "$INIT" == systemd ]] && systemctl list-units --state=failed --no-legend --plain 2>/dev/null | awk '{print $1}' | sort -u || true; }
do_reboot(){ if [[ "$INIT" == systemd ]]; then systemctl reboot; else shutdown -r now; fi; }
# ---- distro / archive detection ------------------------------------------
detect_distro(){
[[ -r /etc/os-release ]] || die "No /etc/os-release."
# shellcheck disable=SC1091
. /etc/os-release
DERIV=0
# codename: try several sources (older Debian lacks VERSION_CODENAME)
CODENAME="${VERSION_CODENAME:-}"
[[ -z "$CODENAME" ]] && CODENAME="$(lsb_release -cs 2>/dev/null || true)"
# from VERSION="9 (stretch)" -> stretch
[[ -z "$CODENAME" || "$CODENAME" == "n/a" ]] && CODENAME="$(sed -n 's/.*(\([a-z][a-z]*\)).*/\1/p' <<<"${VERSION:-}")"
# Debian: derive from /etc/debian_version if it is a codename (e.g. buster/sid)
[[ -z "$CODENAME" && -r /etc/debian_version ]] && grep -qiE '^[a-z]+/' /etc/debian_version 2>/dev/null && \
CODENAME="$(cut -d/ -f1 /etc/debian_version)"
# last resort: map Debian major -> codename
if [[ -z "$CODENAME" && "${ID:-}" == debian ]]; then
case "${VERSION_ID%%.*}" in
8) CODENAME=jessie;; 9) CODENAME=stretch;; 10) CODENAME=buster;;
11) CODENAME=bullseye;; 12) CODENAME=bookworm;; 13) CODENAME=trixie;;
esac
fi
[[ -n "$CODENAME" && "$CODENAME" != "n/a" ]] || die "Cannot determine release codename (got '${CODENAME:-}'). Install lsb-release or check /etc/os-release."
VER="${VERSION_ID:-}"; ARCH="$(dpkg --print-architecture 2>/dev/null || echo '?')"
case "${ID:-}" in
debian) DISTRO=debian ;;
ubuntu) DISTRO=ubuntu ;;
*)
case " ${ID_LIKE:-} " in
*ubuntu*) DISTRO=ubuntu; DERIV=1 ;;
*debian*) DISTRO=debian; DERIV=1 ;;
*) die "Unsupported distro ID='${ID:-?}'. diagnose/migrate-plan are read-only and still work; patch supports Debian/Ubuntu." ;;
esac ;;
esac
}
build_sources(){
local T=""; [[ "${TRUST_ARCHIVE:-0}" == 1 ]] && T="[trusted=yes] "
if [[ "$DISTRO" == debian ]]; then
local major="${VER%%.*}"
local secsuite
if [[ -n "$major" && "$major" -ge 11 ]]; then secsuite="${CODENAME}-security"; else secsuite="${CODENAME}/updates"; fi
ARCHIVE_HOST="archive.debian.org"
NEW_SOURCES="# Managed by apt-patch.sh — EOL archive for ${CODENAME}
deb ${T}http://archive.debian.org/debian ${CODENAME} main contrib non-free
deb ${T}http://archive.debian.org/debian-security ${secsuite} main contrib non-free"
CHECK_URL="http://archive.debian.org/debian/dists/${CODENAME}/Release"
else
ARCHIVE_HOST="old-releases.ubuntu.com"
NEW_SOURCES="# Managed by apt-patch.sh — EOL archive for ${CODENAME}
deb ${T}http://old-releases.ubuntu.com/ubuntu ${CODENAME} main restricted universe multiverse
deb ${T}http://old-releases.ubuntu.com/ubuntu ${CODENAME}-updates main restricted universe multiverse
deb ${T}http://old-releases.ubuntu.com/ubuntu ${CODENAME}-security main restricted universe multiverse"
CHECK_URL="http://old-releases.ubuntu.com/ubuntu/dists/${CODENAME}/Release"
fi
}
# ---- evidence -------------------------------------------------------------
new_evid(){ EVID="${EVID_ROOT}/$(hostname -s)-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$EVID"; ln -sfn "$EVID" "${EVID_ROOT}/latest"; info "Evidence: ${EVID}"; }
latest_evid(){ EVID="$(readlink -f "${EVID_ROOT}/latest" 2>/dev/null || true)"; [[ -n "${EVID:-}" && -d "$EVID" ]] || die "No evidence dir. Run 'patch' first."; }
capture_state(){ # $1 = before|after
local tag="$1"
uname -r > "${EVID}/uname-${tag}.txt"
dpkg -l 2>/dev/null | awk '/^ii/{print $2" "$3}' | sort > "${EVID}/dpkg-${tag}.txt"
ss -tlnp > "${EVID}/ports-${tag}.txt" 2>/dev/null || true
failed_units > "${EVID}/failed-${tag}.txt" 2>/dev/null || true
apt-get "${APT_OPTS[@]}" -s upgrade 2>/dev/null | grep -E '^[0-9]+ upgraded' > "${EVID}/upgradable-${tag}.txt" || true
apt list --upgradable 2>/dev/null | grep -v '^Listing' >> "${EVID}/upgradable-${tag}.txt" || true
if command -v apache2ctl >/dev/null 2>&1; then apache2ctl -t > "${EVID}/apache-configtest-${tag}.txt" 2>&1 || true; fi
}
reboot_needed(){
[[ -f /var/run/reboot-required ]] && return 0
local run newest
run="$(uname -r)"
newest="$(ls -1 /boot/vmlinuz-* 2>/dev/null | sed 's#.*/vmlinuz-##' | sort -V | tail -1)"
[[ -n "$newest" && "$newest" != "$run" ]]
}
# move third-party sources aside during the OS transaction; restore afterwards
THIRDPARTY_STASH=""
stash_thirdparty(){
THIRDPARTY_STASH="$(mktemp -d)"
shopt -s nullglob
local moved=0
for f in "$SOURCES_D"/*.list "$SOURCES_D"/*.sources; do
mv -f "$f" "$THIRDPARTY_STASH/"; info " set aside third-party source: $(basename "$f")"; moved=1
done
shopt -u nullglob
[[ "$moved" == 0 ]] && info " (no third-party sources in ${SOURCES_D})"
return 0
}
restore_thirdparty(){
[[ -n "$THIRDPARTY_STASH" && -d "$THIRDPARTY_STASH" ]] || return 0
shopt -s nullglob
for f in "$THIRDPARTY_STASH"/*; do mv -f "$f" "$SOURCES_D/"; done
shopt -u nullglob
rmdir "$THIRDPARTY_STASH" 2>/dev/null || true
info " restored third-party sources."
}
write_summary(){
{
echo "Remediation summary — $(hostname -f)"
echo "Date: $(date)"
echo "OS: ${PRETTY_NAME:-?} (${CODENAME}, ${ARCH}, ${DISTRO})"
echo "Init: ${INIT}"
echo "Kernel before: $(cat "${EVID}/uname-before.txt" 2>/dev/null)"
echo "Kernel now: $(uname -r)"
echo "Patch source: ${ARCHIVE_HOST}"
echo
echo "Outstanding upgrades after run:"
head -1 "${EVID}/upgradable-after.txt" 2>/dev/null
echo
echo "Package count before/after:"
wc -l "${EVID}/dpkg-before.txt" "${EVID}/dpkg-after.txt" 2>/dev/null
} > "${EVID}/SUMMARY.txt"
ok "Summary: ${EVID}/SUMMARY.txt"
}
# ---- commands -------------------------------------------------------------
cmd_diagnose(){
need_root; detect_init; detect_distro; build_sources
echo "==================== DIAGNOSE: $(hostname -f) ===================="
echo "OS: ${PRETTY_NAME:-?} (codename: ${CODENAME}, arch: ${ARCH})"
echo "Distro/init: ${DISTRO}$([[ "$DERIV" == 1 ]] && echo ' (derivative)') / ${INIT}"
echo "Kernel: $(uname -r)"
echo -n "Archive reachable (${ARCHIVE_HOST}): "; reachable "$CHECK_URL" && echo YES || echo "NO (check access/DNS)"
echo "Current APT sources:"; grep -rhE '^\s*deb ' "$SOURCES_MAIN" "$SOURCES_D"/ 2>/dev/null | sed 's/^/ /' | head -20
echo "apt-get update (current sources):"
apt-get "${APT_OPTS[@]}" update 2>&1 | grep -iE 'Err|404|NO_PUBKEY|no longer|Release' | sed 's/^/ /' | head -12 || echo " (clean)"
echo -n "Pending upgrades: "; apt list --upgradable 2>/dev/null | grep -vc '^Listing' || true
echo "Web-facing listeners:"; ss -tlnp 2>/dev/null | grep -E ':(80|443)\b' | grep -oE '"[a-z0-9_-]+"' | sort -u | sed 's/^/ /' || echo " (none on 80/443)"
preflight_risk
if [[ ${#RISK[@]} -eq 0 ]]; then echo "Risk: none elevated"
else echo "Risk signals:"; printf ' - %s\n' "${RISK[@]}"; [[ ${#RISK[@]} -ge 2 ]] && echo " => REBUILD candidate (patch would require --force)"; fi
echo "==============================================================="
}
cmd_patch(){
local auto_yes=0 dist=0 keep_tp=0; TRUST_ARCHIVE=0; FORCE=0
for a in "$@"; do case "$a" in
--yes) auto_yes=1 ;; --dist-upgrade) dist=1 ;; --with-thirdparty) keep_tp=1 ;; --trust-archive) TRUST_ARCHIVE=1 ;; --force) FORCE=1 ;;
esac; done
need_root; detect_init; detect_distro; build_sources; new_evid
echo; warn "Host: $(hostname -f) | ${PRETTY_NAME:-?} (${CODENAME}, ${ARCH}) | init: ${INIT}"
[[ "$DERIV" == 1 ]] && warn "Detected as a ${DISTRO} derivative — archive URLs assume ${DISTRO}; verify before proceeding."
preflight_risk; preflight_gate
confirm "Has a VMware/vCenter snapshot of this server been taken?" || die "Aborted. Take a snapshot first, then re-run."
info "== PHASE 1: source preparation =="
reachable "$CHECK_URL" || die "Archive not reachable: ${CHECK_URL}. This release may still be supported (use normal mirrors) or access is blocked."
cp -a "$SOURCES_MAIN" "${EVID}/sources.list.backup" 2>/dev/null || true
mkdir -p "${EVID}/sources.list.d.backup"; cp -a "$SOURCES_D"/. "${EVID}/sources.list.d.backup/" 2>/dev/null || true
printf '%s\n' "$NEW_SOURCES" > "$SOURCES_MAIN"
ok "Wrote archive sources to ${SOURCES_MAIN}:"; sed 's/^/ /' "$SOURCES_MAIN"
[[ "$TRUST_ARCHIVE" == 1 ]] && warn " --trust-archive: OS archive sources marked [trusted=yes] (accepts EOL expired signing keys)."
if [[ "$keep_tp" == 0 ]]; then stash_thirdparty; else warn " keeping third-party sources (--with-thirdparty)"; fi
# clear any stale/corrupt cached index files (e.g. DATA_ERROR_MAGIC on Translation-*)
rm -rf /var/lib/apt/lists/partial/* /var/lib/apt/lists/*Translation* 2>/dev/null || true
info "== PHASE 2: refresh indexes + capture BEFORE =="
set +e
apt-get "${APT_OPTS[@]}" update 2>&1 | tee "${EVID}/apt-update.log" | tail -10
local urc="${PIPESTATUS[0]}"
set -e
# EOL archives are signed with EXPIRED keys (EXPKEYSIG) / missing keys (NO_PUBKEY).
# This is inherent to archive.debian.org; it cannot be "fixed" by updating the keyring.
if grep -qiE 'EXPKEYSIG|NO_PUBKEY|is not signed' "${EVID}/apt-update.log" 2>/dev/null; then
if [[ "$TRUST_ARCHIVE" == 1 ]]; then
warn "Archive signed with expired/absent keys — proceeding because --trust-archive is set."
else
warn "The EOL archive is signed with EXPIRED or missing keys:"
grep -iE 'EXPKEYSIG|NO_PUBKEY' "${EVID}/apt-update.log" | sed 's/^/ /' | head -6
echo
warn "This is normal for archive.${DISTRO}.org EOL releases — the signing keys expired by policy"
warn "and updating the keyring does NOT clear it. To proceed you must consciously trust the"
warn "official archive over HTTP. Re-run with --trust-archive to mark the OS sources [trusted=yes]:"
echo -e " ${c_grn}$0 patch --trust-archive${c_off}"
[[ "$keep_tp" == 0 ]] && restore_thirdparty
die "Stopped: signature verification cannot pass on an EOL archive without --trust-archive."
fi
fi
capture_state before; ok "Captured."
info "== PHASE 3: upgrade =="
local action=upgrade; [[ "$dist" == 1 ]] && action=dist-upgrade
info "Action: apt-get ${action}"
set +e
if [[ "$auto_yes" == 1 ]]; then
DEBIAN_FRONTEND=noninteractive apt-get "${APT_OPTS[@]}" -y "$action" 2>&1 | tee "${EVID}/apt-upgrade.log"
else
apt-get "${APT_OPTS[@]}" "$action" 2>&1 | tee "${EVID}/apt-upgrade.log"
fi
local rc="${PIPESTATUS[0]}"; set -e
[[ "$keep_tp" == 0 ]] && restore_thirdparty
[[ "$rc" -eq 0 ]] || die "apt-get ${action} ended with exit ${rc} (aborted or error). See ${EVID}/apt-upgrade.log"
ok "Upgrade complete."
info "== PHASE 4: capture AFTER + validation =="
capture_state after
dpkg -l 2>/dev/null | awk '/^ii/ && ($2 ~ /^(apache2|nginx|openssl|libssl|linux-image|openssh-server|libc6|systemd)/){print $2" "$3}' > "${EVID}/versions-after.txt" || true
if command -v apache2ctl >/dev/null 2>&1; then apache2ctl -t >/dev/null 2>&1 && ok "apache2 configtest OK." || warn "apache2ctl -t reports an error — check before reboot."; fi
# kept-back packages (need dist-upgrade)
local kept; kept="$(grep -A50 'kept back' "${EVID}/apt-upgrade.log" 2>/dev/null | grep -vE 'kept back' | tr -s ' ' '\n' | grep -v '^$' | head -20 || true)"
[[ -n "$kept" && "$dist" == 0 ]] && warn "Some packages were kept back; re-run with --dist-upgrade to complete: $(echo "$kept" | paste -sd' ' -)"
local pend; pend="$(apt list --upgradable 2>/dev/null | grep -vc '^Listing' || true)"
[[ "$pend" -eq 0 ]] && ok "No outstanding upgrades. <- key ticket evidence." || warn "${pend} upgrade(s) still pending (see below / try --dist-upgrade)."
write_summary
info "== PHASE 5: reboot =="
reboot_needed && warn "Kernel/library updates require a reboot (/var/run/reboot-required or newer kernel installed)." \
|| info "Reboot not strictly flagged, but advised after a large upgrade."
if confirm "Reboot now?"; then
ss -tlnp 2>/dev/null | grep -E ':(80|443)\b' > "${EVID}/ports-before-reboot.txt" || true
info "Rebooting (${INIT}). After boot run: $0 verify [https://test-portal]"; do_reboot
else
warn "Reboot skipped. After a manual reboot run: $0 verify [https://test-portal]"
fi
}
cmd_verify(){
local do_reset=0 portal=""
for a in "$@"; do case "$a" in --reset-failed) do_reset=1 ;; http*://*) portal="$a" ;; esac; done
need_root; detect_init; detect_distro; latest_evid
echo "==================== POST-REBOOT VERIFY: $(hostname -f) ===================="
echo "Kernel: $(uname -r)"
echo "System state: $(sys_state)"
if [[ "$INIT" == systemd ]]; then
local current baseline newf
current="$(failed_units)"; baseline="$(sort -u "${EVID}/failed-before.txt" 2>/dev/null || true)"
if [[ -z "$current" ]]; then ok "No failed units."
else
echo "Failed units:"; echo "$current" | sed 's/^/ /'
newf="$(comm -13 <(echo "$baseline") <(echo "$current") 2>/dev/null | grep -v '^$' || true)"
local pre; pre="$(comm -12 <(echo "$baseline") <(echo "$current") 2>/dev/null | grep -v '^$' || true)"
[[ -n "$pre" ]] && warn " Pre-existing (failed before patch): $(echo "$pre" | paste -sd' ' -)"
[[ -n "$newf" ]] && warn " NEW since patch/reboot: $(echo "$newf" | paste -sd' ' -)"
local u st
for u in $current; do
st="$(systemctl is-enabled "$u" 2>/dev/null || true)"
if [[ "$st" == "disabled" || "$st" == "static" ]]; then
if [[ "$do_reset" == 1 ]]; then confirm " Reset failed DISABLED unit '${u}'?" && systemctl reset-failed "$u" && ok " reset-failed ${u}"
else info " '${u}' is ${st}; clear with: systemctl reset-failed ${u}"; fi
else warn " '${u}' is ${st} — real failure, investigate."; fi
done
fi
else
warn "sysvinit host — no aggregate failed-unit state. Checking key services by port/status instead."
fi
echo -n "Web services: "
{ echo -n "apache2=$(svc_active apache2) "; echo -n "nginx=$(svc_active nginx) "; } 2>/dev/null; echo
ss -tlnp 2>/dev/null | grep -E ':(80|443)\b' > "${EVID}/ports-after-reboot.txt" || true
if [[ -f "${EVID}/ports-before-reboot.txt" ]]; then
if diff -q <(grep -oE ':(80|443)\b' "${EVID}/ports-before-reboot.txt"|sort -u) \
<(grep -oE ':(80|443)\b' "${EVID}/ports-after-reboot.txt" |sort -u) >/dev/null
then echo " Ports 80/443: listening as before reboot (OK)."
else warn " Ports 80/443 differ pre/post reboot — check."; fi
fi
if [[ -n "$portal" ]]; then
echo "Functional test: ${portal}"; reachable_headers "$portal"
fi
echo "======================================================================"
ok "Verification recorded. Evidence: ${EVID} (bundle with: $0 bundle)"
}
reachable_headers(){ if command -v curl >/dev/null 2>&1; then curl -kIs "$1" | head -1 | sed 's/^/ /'; else wget -q -S -O /dev/null "$1" 2>&1 | grep -m1 HTTP | sed 's/^/ /'; fi; }
cmd_cleanup_kernels(){
need_root
info "Preview (nothing removed):"; apt-get -s autoremove --purge 2>/dev/null | grep -iE 'linux-image|REMOV' | sed 's/^/ /' | head -20 || true
confirm "Run 'apt-get autoremove --purge' to clear old kernels/packages?" || { info "Skipped."; return 0; }
DEBIAN_FRONTEND=noninteractive apt-get -y autoremove --purge
ok "Done. Installed kernels:"; dpkg -l 'linux-image-*' 2>/dev/null | awk '/^ii/{print " "$2}'
}
cmd_migrate_plan(){
need_root; detect_init; detect_distro
local out="/root/migrate-plan-$(hostname -s).md"; local h; h="$(hostname -f)"
have(){ command -v "$1" >/dev/null 2>&1; }
info "Building migration-assessment report -> ${out}"
{
echo "# Migration assessment — ${h}"
echo; echo "_Generated $(date) by apt-patch.sh migrate-plan_"; echo
echo "## System"; echo
echo "| Field | Value |"; echo "|---|---|"
echo "| Hostname | ${h} |"
echo "| OS | ${PRETTY_NAME:-?} (codename ${CODENAME}) |"
echo "| Architecture | ${ARCH} |"
echo "| Init system | ${INIT} |"
echo "| Kernel | $(uname -r) |"
echo "| Virtualization | $(systemd-detect-virt 2>/dev/null || echo unknown) |"
echo "| CPU cores | $(nproc 2>/dev/null || echo '?') |"
echo "| Memory | $(free -h 2>/dev/null | awk '/Mem:/{print $2}') |"
echo "| Root FS used | $(df -h / 2>/dev/null | awk 'NR==2{print $3" / "$2" ("$5")"}') |"
echo "| IPv4 | $(hostname -I 2>/dev/null | tr ' ' ',' | sed 's/,$//') |"
echo
echo "## Listening sockets (TCP)"; echo; echo '```'
ss -tlnp 2>/dev/null | awk 'NR>1{print $4" "$6}' | sed -E 's/users:\(\("([^"]+)".*/\1/' | sort -u || true
echo '```'; echo
echo "## Application stacks detected"; echo
{ have apache2ctl && echo "- Apache: $(apache2ctl -v 2>/dev/null | awk -F': ' '/version/{print $2; exit}')";
have nginx && echo "- nginx: $(nginx -v 2>&1 | sed 's#.*/##')";
have php && echo "- PHP: $(php -v 2>/dev/null | head -1 | awk '{print $2}')";
have docker && echo "- Docker: $(docker --version 2>/dev/null | awk '{print $3}' | tr -d ,)";
have mysql && echo "- MySQL/MariaDB client present";
} 2>/dev/null
have apache2ctl || have nginx || echo "- (no web server detected)"
echo
echo "## Package inventory"; echo
echo "- Total installed packages: **$(dpkg -l 2>/dev/null | grep -c '^ii')**"
echo
echo "### Packages not available from any configured repo (obsolete / third-party / local)"; echo
echo "Installed packages with no candidate in the current APT indexes — these need"; echo "re-provisioning or a vendor repo on the target OS:"; echo; echo '```'
local avail; avail="$(mktemp)"
grep -h '^Package: ' /var/lib/apt/lists/*_Packages 2>/dev/null | awk '{print $2}' | sort -u > "$avail"
if [[ -s "$avail" ]]; then
comm -23 <(dpkg-query -W -f='${Package}\n' 2>/dev/null | sort -u) "$avail"
else
echo "(no package indexes present — run apt-get update against the archive first for accurate detection)"
fi
rm -f "$avail"
echo '```'; echo
echo "## Migration notes"; echo
if [[ "$DISTRO" == debian ]]; then
echo "- **Recommended target:** current Debian stable (12/13) via staged dist-upgrade, or rebuild."
echo "- **Bridge:** Freexian ELTS provides post-EOL security patches for older Debian."
else
echo "- **Recommended target:** a supported Ubuntu LTS (rebuild or do-release-upgrade), or migrate."
echo "- **Bridge:** Ubuntu Pro (ESM) provides post-EOL security patches."
fi
[[ "$ARCH" == i386 ]] && echo "- **NOTE: i386 (32-bit).** Modern releases drop 32-bit x86; plan an amd64 rebuild."
[[ "$INIT" != systemd ]] && echo "- **NOTE: ${INIT} init** (not systemd); target release uses systemd — expect unit/service changes."
echo
} > "$out"
ok "Report written: ${out}"
}
cmd_bundle(){ need_root; latest_evid; local o="${EVID}.tar.gz"; tar -czf "$o" -C "$(dirname "$EVID")" "$(basename "$EVID")"; ok "Bundled: ${o}"; echo "$o"; }
# ---- preflight risk assessment -------------------------------------------
declare -a RISK
preflight_risk(){
RISK=()
case "$ARCH" in
i386|armel|armhf|powerpc|mips*) RISK+=("32-bit/legacy arch (${ARCH}); modern releases drop it — rebuild likely targets a different arch") ;;
esac
local run newest
run="$(uname -r)"
newest="$(ls -1 /boot/vmlinuz-* 2>/dev/null | sed 's#.*/vmlinuz-##' | sort -V | tail -1)"
[[ -n "$newest" && "$newest" != "$run" ]] && RISK+=("running kernel ${run} is not the newest installed (${newest}) — a prior upgrade was never rebooted")
if dpkg -l 2>/dev/null | awk '/^ii/{print $2}' | grep -qiE '^(xserver-xorg-core|lightdm|gdm3?|libreoffice-core|gnome-shell|task-desktop)(:.*)?$'; then
RISK+=("desktop packages present (Xorg / display-manager / LibreOffice) on a server")
fi
[[ "$INIT" != systemd ]] && RISK+=("legacy init (${INIT}); a supported target uses systemd — expect service/unit changes")
local avail obs
avail="$(grep -h '^Package: ' /var/lib/apt/lists/*_Packages 2>/dev/null | awk '{print $2}' | sort -u)"
if [[ -n "$avail" ]]; then
obs="$(comm -23 <(dpkg-query -W -f='${Package}\n' 2>/dev/null | sort -u) <(echo "$avail") | wc -l)"
[[ "${obs:-0}" -gt 150 ]] && RISK+=("${obs} installed packages have no candidate in the archive — system was likely dragged across releases")
fi
}
preflight_gate(){ # honors FORCE
if [[ ${#RISK[@]} -eq 0 ]]; then ok "Preflight: no elevated-risk signals."; return 0; fi
warn "Preflight risk signals (${#RISK[@]}):"; printf ' - %s\n' "${RISK[@]}"
if [[ ${#RISK[@]} -ge 2 ]]; then
echo
warn "This host looks like a REBUILD candidate, not a patch target."
warn "Automated patching risks leaving it unbootable/half-upgraded; migrating the"
warn "application to a fresh supported build is the sounder path."
if [[ "${FORCE:-0}" == 1 ]]; then
warn "--force is set — proceeding anyway. You own the risk (ensure snapshot + console access)."
else
warn "To override and patch anyway, re-run with --force."
die "Stopped by preflight (high risk). Re-run with --force to override."
fi
fi
return 0
}
main(){
local cmd="${1:-}"; shift || true
case "$cmd" in
diagnose) cmd_diagnose ;;
migrate-plan) cmd_migrate_plan ;;
patch) cmd_patch "$@" ;;
cleanup-kernels) cmd_cleanup_kernels ;;
verify) cmd_verify "$@" ;;
bundle) cmd_bundle ;;
*) sed -n '2,33p' "$0"; exit 1 ;;
esac
}
main "$@"