#!/bin/bash

#
# SYNOPSIS
#     Verify Threat Hunting Lab Setup (Linux)
#     
# DESCRIPTION
#     This script verifies that all artifacts were created successfully by the setup script.
#     Use this to confirm the lab is ready for students.
#     
# NOTES
#     Author: Threat Hunting Lab
#     Can run with or without sudo (some checks may require sudo for full visibility)
#

# Color codes
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
RED='\033[0;31m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Lab Setup Verification Script${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

TOTAL_CHECKS=0
PASSED_CHECKS=0
FAILED_CHECKS=0

# Function to test artifacts
test_artifact() {
    local name="$1"
    local category="$2"
    local test_command="$3"
    
    ((TOTAL_CHECKS++))
    echo -ne "[$category] Testing: $name..."
    
    if eval "$test_command" &>/dev/null; then
        echo -e " ${GREEN}✓ FOUND${NC}"
        ((PASSED_CHECKS++))
        return 0
    else
        echo -e " ${RED}✗ NOT FOUND${NC}"
        ((FAILED_CHECKS++))
        return 1
    fi
}

echo -e "${YELLOW}Checking for suspicious artifacts...${NC}"
echo ""

# ============================================
# USER CHECKS
# ============================================
echo -e "${CYAN}[USERS]${NC}"

test_artifact "User: svc_backup" "USER" "id svc_backup"
test_artifact "User: admin_temp" "USER" "id admin_temp"
test_artifact "User: webadmin" "USER" "id webadmin"

echo ""

# ============================================
# GROUP CHECKS
# ============================================
echo -e "${CYAN}[GROUPS]${NC}"

test_artifact "Group: remoteadmins" "GROUP" "getent group remoteadmins"
test_artifact "Group: backupoperators_custom" "GROUP" "getent group backupoperators_custom"

echo ""

# ============================================
# GROUP MEMBERSHIP CHECKS
# ============================================
echo -e "${CYAN}[GROUP MEMBERSHIPS]${NC}"

test_artifact "svc_backup in remoteadmins" "MEMBERSHIP" "groups svc_backup | grep -q remoteadmins"
test_artifact "admin_temp in backupoperators_custom" "MEMBERSHIP" "groups admin_temp | grep -q backupoperators_custom"
test_artifact "webadmin in sudo group" "MEMBERSHIP" "groups webadmin | grep -q sudo"

echo ""

# ============================================
# NETWORK LISTENER CHECKS
# ============================================
echo -e "${CYAN}[NETWORK]${NC}"

test_artifact "Listener: Port 4444" "NETWORK" "netstat -tuln 2>/dev/null | grep -q ':4444 ' || ss -tuln 2>/dev/null | grep -q ':4444 '"
test_artifact "Listener: Port 8888" "NETWORK" "netstat -tuln 2>/dev/null | grep -q ':8888 ' || ss -tuln 2>/dev/null | grep -q ':8888 '"
test_artifact "Listener: Port 31337" "NETWORK" "netstat -tuln 2>/dev/null | grep -q ':31337 ' || ss -tuln 2>/dev/null | grep -q ':31337 '"

test_artifact "PID File: listener_4444.pid" "NETWORK" "test -f /var/run/listener_4444.pid"
test_artifact "PID File: listener_8888.pid" "NETWORK" "test -f /var/run/listener_8888.pid"
test_artifact "PID File: listener_31337.pid" "NETWORK" "test -f /var/run/listener_31337.pid"

echo ""

# ============================================
# SERVICE CHECKS
# ============================================
echo -e "${CYAN}[SERVICES]${NC}"

test_artifact "Service: system-update-custom.service" "SERVICE" "systemctl list-unit-files | grep -q system-update-custom.service"
test_artifact "Service Directory: /opt/system_services" "SERVICE" "test -d /opt/system_services"
test_artifact "Service Script: update_service.sh" "SERVICE" "test -f /opt/system_services/update_service.sh"
test_artifact "Service Executable: update_service.sh" "SERVICE" "test -x /opt/system_services/update_service.sh"

echo ""

# ============================================
# CRON JOB CHECKS
# ============================================
echo -e "${CYAN}[CRON JOBS]${NC}"

test_artifact "Cron: SystemMaintenanceTask" "CRON" "crontab -l 2>/dev/null | grep -q system_maintenance.sh"
test_artifact "Cron: DataBackupTask" "CRON" "crontab -l 2>/dev/null | grep -q data_backup.sh"
test_artifact "Cron Script: system_maintenance.sh" "CRON" "test -f /opt/scheduled_tasks/system_maintenance.sh"
test_artifact "Cron Script: data_backup.sh" "CRON" "test -f /opt/scheduled_tasks/data_backup.sh"

echo ""

# ============================================
# PROCESS CHECKS
# ============================================
echo -e "${CYAN}[PROCESSES]${NC}"

test_artifact "Process Script: suspicious_updater.sh" "PROCESS" "test -f /opt/updater/suspicious_updater.sh"
test_artifact "Process Script: data_collector.sh" "PROCESS" "test -f /opt/collector/data_collector.sh"

test_artifact "Running Process: suspicious_updater.sh" "PROCESS" "pgrep -f suspicious_updater.sh"
test_artifact "Running Process: data_collector.sh" "PROCESS" "pgrep -f data_collector.sh"

test_artifact "PID File: suspicious_updater.pid" "PROCESS" "test -f /var/run/suspicious_updater.pid"
test_artifact "PID File: data_collector.pid" "PROCESS" "test -f /var/run/data_collector.pid"

echo ""

# ============================================
# FILE CHECKS
# ============================================
echo -e "${CYAN}[FILES]${NC}"

test_artifact "File: /tmp/system_config.txt" "FILE" "test -f /tmp/system_config.txt"
test_artifact "File: /opt/credentials.txt" "FILE" "test -f /opt/credentials.txt"

test_artifact "Permissions: system_config.txt (777)" "FILE" "test \$(stat -c '%a' /tmp/system_config.txt 2>/dev/null) = '777'"
test_artifact "Permissions: credentials.txt (777)" "FILE" "test \$(stat -c '%a' /opt/credentials.txt 2>/dev/null) = '777'"

echo ""

# ============================================
# SETUID/SETGID CHECKS
# ============================================
echo -e "${CYAN}[SETUID/SETGID]${NC}"

test_artifact "SETUID Binary: /tmp/find_backup" "SETUID" "test -f /tmp/find_backup"
test_artifact "SETUID Bit Set: /tmp/find_backup" "SETUID" "test -u /tmp/find_backup"

echo ""

# ============================================
# BASH HISTORY CHECKS
# ============================================
echo -e "${CYAN}[BASH HISTORY]${NC}"

test_artifact "Suspicious History: wget malicious" "HISTORY" "grep -q 'malicious-domain' /root/.bash_history 2>/dev/null"
test_artifact "Suspicious History: nc listener" "HISTORY" "grep -q 'nc -lvp' /root/.bash_history 2>/dev/null"
test_artifact "Suspicious History: backdoor key" "HISTORY" "grep -q 'backdoor_key' /root/.bash_history 2>/dev/null"

echo ""

# ============================================
# LOG FILE CHECK
# ============================================
echo -e "${CYAN}[LOGS]${NC}"

test_artifact "Artifact Log: ThreatHuntingLab_Artifacts.txt" "LOG" "test -f ThreatHuntingLab_Artifacts.txt"

echo ""

# ============================================
# SUMMARY
# ============================================
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Verification Summary${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Calculate success rate
if [ $TOTAL_CHECKS -gt 0 ]; then
    SUCCESS_RATE=$(awk "BEGIN {printf \"%.2f\", ($PASSED_CHECKS / $TOTAL_CHECKS) * 100}")
else
    SUCCESS_RATE=0
fi

echo -e "${WHITE}Total Checks:  $TOTAL_CHECKS${NC}"
echo -e "${GREEN}Passed:        $PASSED_CHECKS${NC}"
echo -e "${RED}Failed:        $FAILED_CHECKS${NC}"

# Color code the success rate
if (( $(echo "$SUCCESS_RATE >= 90" | bc -l) )); then
    RATE_COLOR=$GREEN
elif (( $(echo "$SUCCESS_RATE >= 70" | bc -l) )); then
    RATE_COLOR=$YELLOW
else
    RATE_COLOR=$RED
fi

echo -e "${RATE_COLOR}Success Rate:  $SUCCESS_RATE%${NC}"
echo ""

# Overall status
if [ $FAILED_CHECKS -eq 0 ]; then
    echo -e "${GREEN}✓ All artifacts created successfully!${NC}"
    echo -e "${GREEN}✓ Lab is ready for students!${NC}"
elif [ $FAILED_CHECKS -le 3 ]; then
    echo -e "${YELLOW}⚠ Most artifacts created, but some are missing.${NC}"
    echo -e "${YELLOW}⚠ Review failed checks above.${NC}"
    echo -e "${YELLOW}⚠ Lab may still be usable depending on which artifacts failed.${NC}"
else
    echo -e "${RED}✗ Many artifacts are missing!${NC}"
    echo -e "${RED}✗ Please re-run Setup-ThreatHuntingLab.sh${NC}"
    echo -e "${RED}✗ Ensure you run it with sudo${NC}"
fi

echo ""

# ============================================
# DETAILED RECOMMENDATIONS
# ============================================
if [ $FAILED_CHECKS -gt 0 ]; then
    echo -e "${CYAN}========================================${NC}"
    echo -e "${CYAN}  Troubleshooting Recommendations${NC}"
    echo -e "${CYAN}========================================${NC}"
    echo ""
    
    echo -e "${YELLOW}Common Issues:${NC}"
    echo -e "${WHITE}  1. Setup script was not run with sudo${NC}"
    echo -e "${WHITE}  2. Netcat (nc) is not installed${NC}"
    echo -e "${WHITE}  3. Firewall blocked network listeners${NC}"
    echo -e "${WHITE}  4. Processes were terminated${NC}"
    echo -e "${WHITE}  5. SELinux or AppArmor blocked operations${NC}"
    echo ""
    
    echo -e "${YELLOW}Recommended Actions:${NC}"
    echo -e "${WHITE}  1. Re-run Setup-ThreatHuntingLab.sh with sudo${NC}"
    echo -e "${WHITE}  2. Install netcat: sudo apt-get install netcat${NC}"
    echo -e "${WHITE}  3. Check system logs: journalctl -xe${NC}"
    echo -e "${WHITE}  4. Verify no port conflicts: netstat -tuln${NC}"
    echo -e "${WHITE}  5. Check for process termination: ps aux | grep suspicious${NC}"
    echo ""
fi

# ============================================
# STUDENT READINESS CHECK
# ============================================
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Student Readiness Checklist${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Calculate if setup is mostly complete (80% threshold)
SETUP_COMPLETE=false
if (( $(echo "$SUCCESS_RATE >= 80" | bc -l) )); then
    SETUP_COMPLETE=true
fi

# Check for documentation files
STUDENT_GUIDE=false
[[ -f "Student-Hunting-Guide.md" ]] && STUDENT_GUIDE=true

COMMAND_REF=false
[[ -f "test.txt" ]] && COMMAND_REF=true

QUICK_REF=false
[[ -f "Quick-Reference-Card.md" ]] && QUICK_REF=true

ARTIFACT_LOG=false
[[ -f "ThreatHuntingLab_Artifacts.txt" ]] && ARTIFACT_LOG=true

README_LINUX=false
[[ -f "README_LINUX_SCRIPTS.md" ]] && README_LINUX=true

# Display checklist
print_checklist_item() {
    local item="$1"
    local status="$2"
    
    if [ "$status" = true ]; then
        echo -e "  ${GREEN}[✓] $item${NC}"
    else
        echo -e "  ${RED}[✗] $item${NC}"
    fi
}

print_checklist_item "Setup script completed" "$SETUP_COMPLETE"
print_checklist_item "Student guide available" "$STUDENT_GUIDE"
print_checklist_item "Command reference available" "$COMMAND_REF"
print_checklist_item "Quick reference card available" "$QUICK_REF"
print_checklist_item "Artifact log created" "$ARTIFACT_LOG"
print_checklist_item "Linux README available" "$README_LINUX"

echo ""

# Overall readiness
READY_COUNT=0
[ "$SETUP_COMPLETE" = true ] && ((READY_COUNT++))
[ "$STUDENT_GUIDE" = true ] && ((READY_COUNT++))
[ "$COMMAND_REF" = true ] && ((READY_COUNT++))
[ "$QUICK_REF" = true ] && ((READY_COUNT++))
[ "$ARTIFACT_LOG" = true ] && ((READY_COUNT++))
[ "$README_LINUX" = true ] && ((READY_COUNT++))

if [ $READY_COUNT -eq 6 ]; then
    echo -e "${GREEN}✓ Lab is fully ready for students!${NC}"
elif [ $READY_COUNT -ge 3 ]; then
    echo -e "${YELLOW}⚠ Lab is partially ready - some documentation missing${NC}"
else
    echo -e "${RED}✗ Lab needs more preparation${NC}"
fi

echo ""

# ============================================
# DETAILED ARTIFACT STATUS
# ============================================
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Detailed Artifact Status${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

echo -e "${YELLOW}Active Network Listeners:${NC}"
if command -v netstat &>/dev/null; then
    netstat -tuln 2>/dev/null | grep -E ":(4444|8888|31337) " || echo "  None found"
elif command -v ss &>/dev/null; then
    ss -tuln 2>/dev/null | grep -E ":(4444|8888|31337) " || echo "  None found"
else
    echo "  netstat/ss not available"
fi
echo ""

echo -e "${YELLOW}Running Suspicious Processes:${NC}"
ps aux | grep -E "(suspicious_updater|data_collector)" | grep -v grep || echo "  None found"
echo ""

echo -e "${YELLOW}Suspicious Users:${NC}"
getent passwd | grep -E "(svc_backup|admin_temp|webadmin)" || echo "  None found"
echo ""

echo -e "${YELLOW}Active Cron Jobs:${NC}"
crontab -l 2>/dev/null | grep -E "(system_maintenance|data_backup)" || echo "  None found"
echo ""

echo -e "${YELLOW}Systemd Services:${NC}"
systemctl list-unit-files | grep -i "system-update-custom" || echo "  None found"
echo ""

echo -e "${CYAN}========================================${NC}"
echo ""
