scripts/hosts/guard/pacman-hooks/pacman-post-relock-hosts.sh

51 lines
1.5 KiB
Bash
Raw Normal View History

2025-10-13 10:21:35 +02:00
#!/usr/bin/env bash
# Post-transaction hook to re-apply hosts guard protections (single-layer ro bind)
TARGET=/etc/hosts
ENFORCE=/usr/local/sbin/enforce-hosts.sh
LOGTAG=hosts-guard-hook
2025-11-01 15:36:22 +01:00
mount_layers_count() { awk '$5=="/etc/hosts"{c++} END{print c+0}' /proc/self/mountinfo 2> /dev/null || echo 0; }
2025-10-13 10:21:35 +02:00
collapse_mounts() {
local i=0
2025-11-01 15:36:22 +01:00
if command -v mountpoint > /devnull 2>&1; then
2025-10-13 10:21:35 +02:00
while mountpoint -q "$TARGET"; do
2025-11-01 15:36:22 +01:00
umount -l "$TARGET" > /dev/null 2>&1 || break
i=$((i + 1))
((i > 20)) && break
2025-10-13 10:21:35 +02:00
done
else
local cnt
cnt=$(mount_layers_count)
2025-11-01 15:36:22 +01:00
while ((cnt > 1)); do
umount -l "$TARGET" > /dev/null 2>&1 || break
i=$((i + 1))
((i > 20)) && break
2025-10-13 10:21:35 +02:00
cnt=$(mount_layers_count)
done
fi
}
# Ensure we end with a single read-only bind mount layer
logger -t "$LOGTAG" "post: relocking /etc/hosts (starting)"
2025-11-01 15:36:22 +01:00
echo "$(date -Is) post-relock(start)" >> /run/hosts-guard-hook.log 2> /dev/null || true
2025-10-13 10:21:35 +02:00
collapse_mounts
2025-11-01 15:36:22 +01:00
if [[ -x $ENFORCE ]]; then
"$ENFORCE" > /dev/null 2>&1 || true
2025-10-13 10:21:35 +02:00
fi
# Apply exactly one ro bind layer
2025-11-01 15:36:22 +01:00
mount --bind "$TARGET" "$TARGET" > /dev/null 2>&1 || true
mount -o remount,ro,bind "$TARGET" > /dev/null 2>&1 || true
2025-10-13 10:21:35 +02:00
# Start only the path watcher; avoid bind-mount service (we already bound once)
2025-11-01 15:36:22 +01:00
if command -v systemctl > /dev/null 2>&1; then
systemctl start hosts-guard.path > /dev/null 2>&1 || true
2025-10-13 10:21:35 +02:00
fi
logger -t "$LOGTAG" "post: relocking /etc/hosts (done)"
2025-11-01 15:36:22 +01:00
echo "$(date -Is) post-relock(done)" >> /run/hosts-guard-hook.log 2> /dev/null || true
2025-10-13 10:21:35 +02:00
exit 0