#!/bin/bash

# Incident Response Phase 1: Discovery & Initial Assessment (Remote Execution)
# Usage: ./phase1.sh <target_host>
# This script runs from operator machine and executes commands remotely via SSH

set -euo pipefail

# Configuration
SCRIPT_VERSION="1.0"
PHASE="phase1-discovery"
SSH_USER="ir"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Check if target host parameter is provided
if [[ $# -ne 1 ]]; then
    echo -e "${RED}Usage: $0 <target_host>${NC}"
    echo -e "${YELLOW}Example: $0 webserver01.company.com${NC}"
    echo -e "${YELLOW}Note: Ensure you have SSH access as 'ir' user to the target host${NC}"
    exit 1
fi

TARGET_HOST="$1"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BASE_DIR="./incident_response"
HOST_DIR="$BASE_DIR/$TARGET_HOST"
PHASE_DIR="$HOST_DIR/$PHASE"
LOG_FILE="$PHASE_DIR/${PHASE}_${TIMESTAMP}.log"
SUMMARY_FILE="$PHASE_DIR/${PHASE}_summary_${TIMESTAMP}.txt"

# Create local directory structure on operator machine
mkdir -p "$PHASE_DIR"

# Logging functions
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" | tee -a "$LOG_FILE"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}" | tee -a "$LOG_FILE"
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARNING] $1${NC}" | tee -a "$LOG_FILE"
}

info() {
    echo -e "${BLUE}[INFO] $1${NC}" | tee -a "$LOG_FILE"
}

# Function to execute remote command via SSH
remote_cmd() {
    local cmd="$1"
    local description="$2"
    local output_file="$3"
    
    log "Executing remotely: $description"
    echo "=== $description ===" >> "$LOG_FILE"
    echo "Target: $TARGET_HOST" >> "$LOG_FILE"
    echo "Command: $cmd" >> "$LOG_FILE"
    echo "Output:" >> "$LOG_FILE"
    
    if ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" >> "$LOG_FILE" 2>&1; then
        info "✓ $description completed"
        if [[ -n "$output_file" ]]; then
            ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" > "$PHASE_DIR/$output_file" 2>&1 || true
        fi
    else
        warn "✗ $description failed or returned non-zero exit code"
    fi
    echo "" >> "$LOG_FILE"
}

# Function to execute remote command with timeout
remote_cmd_timeout() {
    local cmd="$1"
    local description="$2"
    local timeout_sec="$3"
    local output_file="$4"
    
    log "Executing remotely (timeout: ${timeout_sec}s): $description"
    echo "=== $description ===" >> "$LOG_FILE"
    echo "Target: $TARGET_HOST" >> "$LOG_FILE"
    echo "Command: $cmd" >> "$LOG_FILE"
    echo "Output:" >> "$LOG_FILE"
    
    if timeout "$timeout_sec" ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" >> "$LOG_FILE" 2>&1; then
        info "✓ $description completed"
        if [[ -n "$output_file" ]]; then
            timeout "$timeout_sec" ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" > "$PHASE_DIR/$output_file" 2>&1 || true
        fi
    else
        warn "✗ $description failed, timed out, or returned non-zero exit code"
    fi
    echo "" >> "$LOG_FILE"
}

# Test SSH connectivity
test_ssh_connection() {
    log "Testing SSH connectivity to $TARGET_HOST..."
    if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "echo 'SSH connection successful'" >/dev/null 2>&1; then
        error "Cannot connect to $TARGET_HOST as $SSH_USER. Ensure SSH keys are configured and IR lockdown was deployed."
    fi
    info "✓ SSH connection to $TARGET_HOST successful"
}

# Start discovery
log "=== INCIDENT RESPONSE PHASE 1: DISCOVERY & INITIAL ASSESSMENT ==="
log "Target Host: $TARGET_HOST"
log "Operator Machine: $(hostname)"
log "Timestamp: $TIMESTAMP"
log "Local Log Directory: $PHASE_DIR"
log "Starting remote system discovery..."

# Test SSH connection first
test_ssh_connection

# Create summary header
cat > "$SUMMARY_FILE" << EOF
=== INCIDENT RESPONSE PHASE 1 SUMMARY ===
Target Host: $TARGET_HOST
Operator Machine: $(hostname)
Timestamp: $TIMESTAMP
Script Version: $SCRIPT_VERSION
Local Log Directory: $PHASE_DIR

EOF

# 1. Initial System Triage
log "Phase 1.1: Initial System Triage"
remote_cmd "whoami && id" "Current user and privileges" "current_user.txt"
remote_cmd "uname -a" "System information" "system_info.txt"
remote_cmd "cat /etc/os-release 2>/dev/null || cat /etc/redhat-release 2>/dev/null || uname -v" "OS release information" "os_release.txt"
remote_cmd "uptime" "System uptime and load" "uptime.txt"
remote_cmd "w" "Currently logged in users" "logged_users.txt"
remote_cmd "ps aux --forest 2>/dev/null || ps auxwww" "Process tree" "process_tree.txt"
remote_cmd "ps aux | grep -E '(nc|netcat|python|perl|bash|sh)' | grep -v grep" "Suspicious processes" "suspicious_processes.txt"

# 2. Network Discovery
log "Phase 1.2: Network Discovery"
remote_cmd "ip addr show 2>/dev/null || ifconfig -a" "Network interfaces" "network_interfaces.txt"
remote_cmd "ip route 2>/dev/null || route -n" "Routing table" "routing_table.txt"
remote_cmd_timeout "ss -tulpn 2>/dev/null || netstat -tulpn" "Active connections and listening ports" 30 "network_connections.txt"
remote_cmd_timeout "netstat -panut 2>/dev/null || ss -panut" "Network statistics" 30 "netstat_full.txt"
remote_cmd "ss -tulpn 2>/dev/null | grep LISTEN || netstat -tulpn | grep LISTEN" "Listening services" "listening_services.txt"

# 3. User & Access Assessment
log "Phase 1.3: User & Access Assessment"
remote_cmd "cat /etc/passwd | cut -d: -f1" "All system users" "all_users.txt"
remote_cmd "grep -E '/bin/(ba)?sh$' /etc/passwd" "Users with shell access" "shell_users.txt"
remote_cmd "sudo grep -v '*' /etc/shadow 2>/dev/null | grep -v '!' | cut -d: -f1 || echo 'Cannot access shadow file'" "Users with passwords" "users_with_passwords.txt"
remote_cmd "cat /etc/passwd | grep -v -E '(root|daemon|bin|sys|sync|games|man|lp|mail|news|uucp|proxy|www-data|backup|list|irc|gnats|nobody|systemd|syslog)'" "Potentially unauthorized users" "suspicious_users.txt"
remote_cmd "sudo cat /etc/sudoers 2>/dev/null || echo 'Cannot access sudoers'" "Sudoers configuration" "sudoers.txt"
remote_cmd "sudo cat /etc/sudoers.d/* 2>/dev/null || echo 'No additional sudoers files'" "Additional sudoers files" "sudoers_additional.txt"
remote_cmd_timeout "find /home -name '.ssh' -exec ls -la {} \\; 2>/dev/null" "SSH directories" 30 "ssh_directories.txt"
remote_cmd_timeout "find /home -name 'authorized_keys' -exec cat {} \\; 2>/dev/null" "SSH authorized keys" 30 "ssh_authorized_keys.txt"

# 4. File System Assessment
log "Phase 1.4: File System Assessment"
remote_cmd_timeout "find /var/www -name '*.php' -type f -mtime -1 2>/dev/null | head -50" "Recently modified PHP files" 60 "recent_php_files.txt"
remote_cmd_timeout "find /tmp -type f -executable 2>/dev/null | head -20" "Executable files in /tmp" 30 "tmp_executables.txt"
remote_cmd_timeout "find /dev/shm -type f 2>/dev/null | head -20" "Files in /dev/shm" 30 "shm_files.txt"
remote_cmd_timeout "find / -type f -mtime -1 2>/dev/null | grep -v -E '(proc|sys|dev)' | head -50" "Recently modified files" 120 "recent_files.txt"
remote_cmd "cat /etc/crontab 2>/dev/null || echo 'No /etc/crontab'" "System crontab" "system_crontab.txt"
remote_cmd "ls -la /etc/cron.* 2>/dev/null || echo 'No cron directories'" "Cron directories" "cron_directories.txt"
remote_cmd "crontab -l 2>/dev/null || echo 'No user crontab'" "User crontab" "user_crontab.txt"
remote_cmd "sudo crontab -l 2>/dev/null || echo 'No root crontab'" "Root crontab" "root_crontab.txt"

# 5. Service Assessment
log "Phase 1.5: Service Assessment"
remote_cmd "systemctl list-unit-files --state=enabled 2>/dev/null || service --status-all 2>/dev/null" "Enabled services" "enabled_services.txt"
remote_cmd "systemctl list-units --type=service 2>/dev/null || service --status-all 2>/dev/null" "All services status" "all_services.txt"
remote_cmd "ps aux | grep -E '(apache|nginx|httpd)' | grep -v grep" "Web server processes" "web_servers.txt"
remote_cmd "systemctl status apache2 nginx httpd 2>/dev/null || echo 'Web services check complete'" "Web services status" "web_services_status.txt"
remote_cmd "ps aux | grep -E '(mysql|postgres|mongo)' | grep -v grep" "Database processes" "database_processes.txt"
remote_cmd "systemctl status mysql postgresql mongodb 2>/dev/null || echo 'Database services check complete'" "Database services status" "database_services_status.txt"
remote_cmd "systemctl status ssh sshd 2>/dev/null || echo 'SSH service check complete'" "SSH service status" "ssh_service_status.txt"
remote_cmd "ps aux | grep sshd | grep -v grep" "SSH daemon processes" "sshd_processes.txt"

# 6. Log Analysis (Quick Check)
log "Phase 1.6: Log Analysis (Quick Check)"
remote_cmd "sudo tail -100 /var/log/auth.log 2>/dev/null || sudo tail -100 /var/log/secure 2>/dev/null || echo 'No auth logs found'" "Recent authentication logs" "recent_auth_logs.txt"
remote_cmd "sudo tail -100 /var/log/syslog 2>/dev/null || sudo tail -100 /var/log/messages 2>/dev/null || echo 'No system logs found'" "Recent system logs" "recent_system_logs.txt"
remote_cmd "sudo grep 'Failed password' /var/log/auth.log 2>/dev/null | tail -20 || echo 'No failed password attempts found'" "Failed login attempts" "failed_logins.txt"
remote_cmd "sudo lastb | head -20 2>/dev/null || echo 'No bad login records'" "Bad login records" "bad_logins.txt"
remote_cmd "last | head -20" "Successful login records" "successful_logins.txt"

# 7. Red Team Indicator Search
log "Phase 1.7: Red Team Indicator Search"
remote_cmd "ss -tulpn 2>/dev/null | grep -E ':(4444|5555|6666|7777|8080|9999|31337)' || netstat -tulpn 2>/dev/null | grep -E ':(4444|5555|6666|7777|8080|9999|31337)'" "Common backdoor ports" "backdoor_ports.txt"
remote_cmd "ps aux | grep -E '(nc|ncat|socat|bash.*tcp|python.*socket)' | grep -v grep" "Reverse shell patterns" "reverse_shells.txt"
remote_cmd "cat /etc/rc.local 2>/dev/null || echo 'No /etc/rc.local'" "Startup scripts" "startup_scripts.txt"
remote_cmd "ls -la /etc/init.d/ 2>/dev/null | head -20" "Init scripts" "init_scripts.txt"
remote_cmd "systemctl list-unit-files 2>/dev/null | grep -v disabled | grep -v static | head -20 || echo 'No systemd available'" "Active systemd units" "active_systemd_units.txt"

# 8. Generate Summary
log "Phase 1.8: Generating Discovery Summary"

{
    echo "=== CRITICAL FINDINGS ==="
    echo ""
    
    # Check for suspicious users
    SUSPICIOUS_USERS=$(cat "$PHASE_DIR/suspicious_users.txt" 2>/dev/null | grep -v '^$' | wc -l)
    if [[ $SUSPICIOUS_USERS -gt 0 ]]; then
        echo "⚠️  Found $SUSPICIOUS_USERS potentially unauthorized users"
    fi
    
    # Check for backdoor ports
    BACKDOOR_PORTS=$(cat "$PHASE_DIR/backdoor_ports.txt" 2>/dev/null | grep -v '^$' | wc -l)
    if [[ $BACKDOOR_PORTS -gt 0 ]]; then
        echo "🚨 Found $BACKDOOR_PORTS potential backdoor ports"
    fi
    
    # Check for reverse shells
    REVERSE_SHELLS=$(cat "$PHASE_DIR/reverse_shells.txt" 2>/dev/null | grep -v '^$' | wc -l)
    if [[ $REVERSE_SHELLS -gt 0 ]]; then
        echo "🚨 Found $REVERSE_SHELLS potential reverse shell processes"
    fi
    
    # Check for executable files in /tmp
    TMP_EXECUTABLES=$(cat "$PHASE_DIR/tmp_executables.txt" 2>/dev/null | grep -v '^$' | wc -l)
    if [[ $TMP_EXECUTABLES -gt 0 ]]; then
        echo "⚠️  Found $TMP_EXECUTABLES executable files in /tmp"
    fi
    
    echo ""
    echo "=== SYSTEM OVERVIEW ==="
    echo "Target Host: $TARGET_HOST"
    echo "OS: $(cat "$PHASE_DIR/os_release.txt" 2>/dev/null | head -1 || echo 'Unknown')"
    echo "Uptime: $(cat "$PHASE_DIR/uptime.txt" 2>/dev/null | awk '{print $3,$4}' || echo 'Unknown')"
    echo "Users with shell access: $(cat "$PHASE_DIR/shell_users.txt" 2>/dev/null | wc -l || echo '0')"
    echo "Listening services: $(cat "$PHASE_DIR/listening_services.txt" 2>/dev/null | wc -l || echo '0')"
    echo "Active processes: $(cat "$PHASE_DIR/process_tree.txt" 2>/dev/null | wc -l || echo '0')"
    
    echo ""
    echo "=== NEXT STEPS ==="
    echo "1. Review critical findings above"
    echo "2. Analyze suspicious users and processes"
    echo "3. Check backdoor ports and reverse shells"
    echo "4. Proceed to Phase 2: Containment"
    echo ""
    echo "=== FILES GENERATED (LOCAL) ==="
    ls -la "$PHASE_DIR" | grep -v "^total"
    
} >> "$SUMMARY_FILE"

# Final log entries
log "Phase 1 Discovery completed successfully"
log "Summary file: $SUMMARY_FILE"
log "All output files saved locally to: $PHASE_DIR"

# Display summary
echo
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  PHASE 1 DISCOVERY COMPLETE           ${NC}"
echo -e "${GREEN}========================================${NC}"
echo
echo -e "${YELLOW}Target Host:${NC} $TARGET_HOST"
echo -e "${YELLOW}Local Log Directory:${NC} $PHASE_DIR"
echo -e "${YELLOW}Summary File:${NC} $SUMMARY_FILE"
echo
echo -e "${BLUE}Quick Summary:${NC}"
cat "$SUMMARY_FILE" | grep -A 20 "=== CRITICAL FINDINGS ==="
echo
echo -e "${YELLOW}Next: Review findings and proceed to Phase 2 (Containment)${NC}"
echo -e "${GREEN}Command: ./phase2.sh $TARGET_HOST${NC}"