#!/usr/bin/env bash
# CIS Benchmark quick checker for Linux systems.
# Checks common hardening controls from CIS Level 1.
# Usage: sudo bash scripts/cis_check.sh
set -euo pipefail

PASS=0; FAIL=0; WARN=0

check() {
  local desc="$1" result="$2"
  if [ "$result" = "pass" ]; then
    echo "  ✅ $desc"; ((PASS++))
  elif [ "$result" = "fail" ]; then
    echo "  🔴 $desc"; ((FAIL++))
  else
    echo "  ⚠️  $desc"; ((WARN++))
  fi
}

echo "=== CIS Level 1 Quick Check ==="
echo ""

echo "--- Filesystem ---"
check "Separate /tmp partition" "$(mountpoint -q /tmp 2>/dev/null && echo pass || echo fail)"
check "/tmp noexec" "$(mount | grep ' /tmp ' | grep -q noexec && echo pass || echo fail)"

echo ""
echo "--- Services ---"
check "SSH root login disabled" "$(grep -qE '^PermitRootLogin\s+no' /etc/ssh/sshd_config 2>/dev/null && echo pass || echo fail)"
check "SSH protocol 2" "$(grep -qE '^Protocol\s+1' /etc/ssh/sshd_config 2>/dev/null && echo fail || echo pass)"
check "SSH MaxAuthTries ≤ 4" "$(awk '/^MaxAuthTries/{if($2<=4)print "pass";else print "fail"}' /etc/ssh/sshd_config 2>/dev/null || echo warn)"

echo ""
echo "--- User Accounts ---"
check "No UID 0 except root" "$(awk -F: '$3==0{print $1}' /etc/passwd | grep -qv '^root$' && echo fail || echo pass)"
check "Password hashing SHA512" "$(grep -q 'SHA512\|yescrypt' /etc/login.defs 2>/dev/null && echo pass || echo warn)"
check "No empty passwords" "$(awk -F: '($2 == ""){print $1}' /etc/shadow 2>/dev/null | grep -q . && echo fail || echo pass)"

echo ""
echo "--- Network ---"
check "IP forwarding disabled" "$(sysctl -n net.ipv4.ip_forward 2>/dev/null | grep -q 0 && echo pass || echo fail)"
check "ICMP redirects disabled" "$(sysctl -n net.ipv4.conf.all.accept_redirects 2>/dev/null | grep -q 0 && echo pass || echo fail)"
check "Firewall active" "$(systemctl is-active ufw 2>/dev/null || systemctl is-active firewalld 2>/dev/null || iptables -L -n 2>/dev/null | grep -q 'Chain' && echo pass || echo fail)"

echo ""
echo "--- Logging ---"
check "Auditd running" "$(systemctl is-active auditd 2>/dev/null | grep -q active && echo pass || echo warn)"
check "Syslog running" "$(systemctl is-active rsyslog 2>/dev/null | grep -q active && echo pass || echo warn)"

echo ""
echo "=== Summary: $PASS passed, $FAIL failed, $WARN warnings ==="
