#!/bin/bash
# Fresh-baseline-on-boot for CVE-2016-5195 (Dirty COW).
#
# Writes a FRESH, unpredictable marker into the root-owned, actor-read-only
# target file on EVERY boot. The marker is never baked at build time; it is
# regenerated here so an observed change after the exploit can only be the
# result of a write through the COW race, not a pre-seeded or guessable value.
#
# Target file properties (the criterion's observable surface):
#   - owned root:root, mode 0404  -> world-READABLE, NOBODY can write (not even root w/o chmod)
#   - the unprivileged actor can read it but cannot write it
set -euo pipefail

TARGET=/opt/cve/target
mkdir -p /opt/cve

# Fresh random marker: a line the exploit could not have known in advance.
# Fixed byte length keeps the Dirty COW overwrite (which writes in place,
# same length) well-defined for the exploiter/verifier.
MARKER="DIRTYCOW-BASELINE-$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')"

# Write as root, then lock down so the actor can read but never write.
umask 0333
printf '%s\n' "$MARKER" > "$TARGET"
chown root:root "$TARGET"
chmod 0404 "$TARGET"

# Make the privileged baseline trivially re-readable out-of-band by the verifier
# (root channel). This copy is root-only (0400) and is NOT the exploit target.
cp "$TARGET" /root/cve-baseline.txt
chmod 0400 /root/cve-baseline.txt
chown root:root /root/cve-baseline.txt

logger -t cve-baseline "fresh Dirty COW baseline written to ${TARGET} (root:root 0404)"
