#!/usr/bin/env bash
# audit-produksi.sh — audit mini hardening produksi dari berkas snapshot.
# Di server sungguhan, snapshot diambil dari sshd_config, ss, dan systemctl;
# di latihan, nilainya dibekukan agar hasilnya selalu bisa dibandingkan.

ok=0
gagal=0

cek() {
    # $1 = pesan, $2 = status: 0 lolos, selain itu temuan
    if [ "$2" -eq 0 ]; then
        printf '[OK]    %s\n' "$1"
        ok=$((ok+1))
    else
        printf '[CATAT] %s\n' "$1"
        gagal=$((gagal+1))
    fi
}

echo "== Audit Hardening Produksi =="

# 1. SSH: tanpa root, tanpa password, kunci saja
grep -q '^PermitRootLogin no' sshd_config.audit
cek "SSH: PermitRootLogin no" $?
grep -q '^PasswordAuthentication no' sshd_config.audit
cek "SSH: PasswordAuthentication no" $?
grep -q '^PubkeyAuthentication yes' sshd_config.audit
cek "SSH: PubkeyAuthentication yes" $?

# 2. SSH: batasi percobaan gagal
maks_coba=$(awk '/^MaxAuthTries/ {print $2}' sshd_config.audit)
if [ "${maks_coba:-0}" -le 4 ]; then
    cek "SSH: MaxAuthTries ${maks_coba} (<= 4)" 0
else
    cek "SSH: MaxAuthTries ${maks_coba} (harap <= 4)" 1
fi

# 3. Hanya port layanan yang direncanakan
tak_rencana=$(awk '{split($2, a, ":"); if (a[2] != 22 && a[2] != 80 && a[2] != 443) print a[2]}' port-terbuka.txt | tr '\n' ' ')
if [ -z "$tak_rencana" ]; then
    cek "Port terbuka sesuai rencana (22, 80, 443)" 0
else
    cek "Port di luar rencana: ${tak_rencana}" 1
fi

# 4. Service yang tidak terpakai dimatikan
nganggur=$(grep -E '^(cups|avahi-daemon|rpcbind)' service-aktif.txt | cut -d. -f1 | tr '\n' ' ')
if [ -z "$nganggur" ]; then
    cek "Tidak ada service tidak terpakai" 0
else
    cek "Service tidak terpakai: ${nganggur}" 1
fi

total=$((ok+gagal))
echo "Skor: $ok/$total lolos"
if [ "$gagal" -gt 0 ]; then
    echo "Rekomendasi: perbaiki semua [CATAT] sebelum server menghadap internet."
fi
