scripts/hosts/guard/enforce-hosts.sh

33 lines
965 B
Bash
Raw Normal View History

2025-10-01 20:50:56 +02:00
#!/bin/bash
# Template guard script to enforce canonical /etc/hosts
# This will be installed into /usr/local/sbin/enforce-hosts.sh by a setup script.
set -euo pipefail
CANONICAL_SOURCE="/usr/local/share/locked-hosts"
TARGET="/etc/hosts"
LOG_FILE="/var/log/hosts-guard.log"
log() {
2025-11-01 15:36:22 +01:00
printf '%s - %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" | tee -a "$LOG_FILE" >&2
2025-10-01 20:50:56 +02:00
}
2025-11-01 15:36:22 +01:00
if [[ ! -f $CANONICAL_SOURCE ]]; then
log "Canonical hosts not found at $CANONICAL_SOURCE; aborting enforcement"
exit 0
2025-10-01 20:50:56 +02:00
fi
if ! cmp -s "$CANONICAL_SOURCE" "$TARGET"; then
2025-11-01 15:36:22 +01:00
log "Difference detected restoring $TARGET from canonical copy"
cp "$CANONICAL_SOURCE" "$TARGET"
chmod 644 "$TARGET"
2025-10-01 20:50:56 +02:00
else
2025-11-01 15:36:22 +01:00
log "No drift detected (contents identical)"
2025-10-01 20:50:56 +02:00
fi
# Re-apply protective attributes: immutable first, then read-only bind mount handled by separate unit
2025-11-01 15:36:22 +01:00
chattr -i -a "$TARGET" 2> /dev/null || true
2025-10-01 20:50:56 +02:00
chattr +i "$TARGET" || log "Failed to set immutable attribute"
2025-11-01 15:36:22 +01:00
log "Enforcement complete"