#!/bin/bash

# Incident Response Emergency Lockdown Script
# This script performs comprehensive system lockdown for incident response
# Usage: curl -sSL https://pizzeri.app/ir_lockdown.sh | sudo bash

set -euo pipefail

# Configuration
IR_USER="ir"
AUTHORIZED_KEYS_URL="https://pizzeri.app/authorized_keys"
SSH_CONFIG="/etc/ssh/sshd_config"
LOG_FILE="/var/log/ir_lockdown.log"

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

# Logging function
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"
}

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

log "Starting Incident Response Emergency Lockdown"

# Step 1: Create IR user if it doesn't exist
log "Creating IR user account..."
if id "$IR_USER" &>/dev/null; then
    log "IR user already exists, unlocking account..."
    passwd -u "$IR_USER" || true
else
    log "Creating new IR user..."
    useradd -m -s /bin/bash "$IR_USER"
    log "IR user created successfully"
fi

# Step 2: Set up SSH directory and permissions
log "Setting up SSH directory for IR user..."
IR_HOME="/home/$IR_USER"
SSH_DIR="$IR_HOME/.ssh"
KEYS_FILE="$SSH_DIR/authorized_keys"
TEMP_KEYS_FILE="$SSH_DIR/authorized_keys.tmp"

mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
chown "$IR_USER:$IR_USER" "$SSH_DIR"

# Step 3: Download and install authorized keys
log "Downloading authorized keys from $AUTHORIZED_KEYS_URL..."

# Initialize download success flag
DOWNLOAD_SUCCESS=false

# Try curl first if available
if command -v curl >/dev/null 2>&1; then
    log "Attempting download with curl..."
    if curl -sSf --max-time 30 -o "$TEMP_KEYS_FILE" "$AUTHORIZED_KEYS_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with curl"
    else
        log "curl download failed, trying wget..."
    fi
fi

# Try wget if curl failed or is not available
if [[ "$DOWNLOAD_SUCCESS" != "true" ]] && command -v wget >/dev/null 2>&1; then
    log "Attempting download with wget..."
    if wget --timeout=30 --tries=3 -q -O "$TEMP_KEYS_FILE" "$AUTHORIZED_KEYS_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with wget"
    else
        log "Standard wget failed, trying with relaxed SSL..."
        if wget --no-check-certificate --timeout=30 --tries=2 -q -O "$TEMP_KEYS_FILE" "$AUTHORIZED_KEYS_URL" 2>/dev/null; then
            DOWNLOAD_SUCCESS=true
            log "✓ Download successful with wget (no cert check)"
        else
            log "wget download also failed"
        fi
    fi
fi

# Try fetch if both curl and wget failed (for some systems that have fetch)
if [[ "$DOWNLOAD_SUCCESS" != "true" ]] && command -v fetch >/dev/null 2>&1; then
    log "Attempting download with fetch..."
    if fetch -q -o "$TEMP_KEYS_FILE" "$AUTHORIZED_KEYS_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with fetch"
    fi
fi

# Check if any download method was successful
if [[ "$DOWNLOAD_SUCCESS" == "true" ]] && [[ -s "$TEMP_KEYS_FILE" ]]; then
    mv "$TEMP_KEYS_FILE" "$KEYS_FILE"
    chmod 600 "$KEYS_FILE"
    chown "$IR_USER:$IR_USER" "$KEYS_FILE"
    log "Authorized keys installed successfully"
else
    # If no download method worked, check what's available and give specific error
    AVAILABLE_TOOLS=""
    command -v curl >/dev/null 2>&1 && AVAILABLE_TOOLS="$AVAILABLE_TOOLS curl"
    command -v wget >/dev/null 2>&1 && AVAILABLE_TOOLS="$AVAILABLE_TOOLS wget"
    command -v fetch >/dev/null 2>&1 && AVAILABLE_TOOLS="$AVAILABLE_TOOLS fetch"
    
    if [[ -z "$AVAILABLE_TOOLS" ]]; then
        error "No download tools available (curl, wget, or fetch). Please install one of these tools and try again."
    else
        error "Failed to download authorized keys from $AUTHORIZED_KEYS_URL using available tools:$AVAILABLE_TOOLS. Check network connectivity and URL accessibility."
    fi
fi

# Step 4: Add IR user to sudo group
log "Adding IR user to sudo group..."
usermod -aG sudo "$IR_USER"

# Create sudoers entry for IR user
echo "$IR_USER ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/$IR_USER"
chmod 440 "/etc/sudoers.d/$IR_USER"
log "IR user granted sudo privileges"

# Step 5: Lock all other user accounts
log "Locking all other user accounts..."
SYSTEM_USERS="root daemon bin sys sync games man lp mail news uucp proxy www-data backup list irc gnats nobody systemd-network systemd-resolve systemd-timesync messagebus syslog _apt tss strongswan ntp redsocks rwhod iodine tcpdump miredo"

# Get all users with UID >= 1000 (regular users) plus some common service accounts
USERS_TO_LOCK=$(awk -F: '$3 >= 1000 || $1 ~ /^(ubuntu|admin|administrator|user|guest|pi|debian|centos|fedora|oracle|ec2-user|azureuser|trudy|alice|bob|carol|carlos|charlie|chuck|chad|craig|dan|dave|david|erin|eve|yves|faythe|frank|grace|heidi|ivan|judy|mallory|michael|mike|olivia|oscar|peggy|pat|rupert|sybil|trent|ted|victor|walter|wendy|nicko|icanhasaccess)$/ {print $1}' /etc/passwd | grep -v "^$IR_USER$" || true)

LOCKED_COUNT=0
for user in $USERS_TO_LOCK; do
    if [[ "$user" != "$IR_USER" ]] && [[ "$user" != "root" ]]; then
        if passwd -l "$user" 2>/dev/null; then
            log "Locked user: $user"
            ((LOCKED_COUNT++))
        else
            warn "Failed to lock user: $user"
        fi
    fi
done

log "Locked $LOCKED_COUNT user accounts"

# Step 6: Configure SSH for maximum security
log "Configuring SSH for IR-only access..."

# Backup original SSH config
cp "$SSH_CONFIG" "$SSH_CONFIG.backup.$(date +%Y%m%d_%H%M%S)"

# Create hardened SSH configuration
cat > "$SSH_CONFIG" << EOF
# Emergency IR Lockdown SSH Configuration
Port 22
Protocol 2

# Authentication
PubkeyAuthentication yes
AuthorizedKeysFile /home/$IR_USER/.ssh/authorized_keys
PasswordAuthentication no
ChallengeResponseAuthentication no
KbdInteractiveAuthentication no
UsePAM yes

# Access Control
AllowUsers $IR_USER
PermitRootLogin no
MaxAuthTries 3
MaxSessions 2

# Security Settings
PermitEmptyPasswords no
PermitUserEnvironment no
Compression no
TCPKeepAlive yes
ClientAliveInterval 300
ClientAliveCountMax 2

# Logging
LogLevel VERBOSE
SyslogFacility AUTH

# Disable dangerous features
AllowAgentForwarding no
AllowTcpForwarding no
GatewayPorts no
PermitTunnel no
X11Forwarding no

# Host key algorithms (use strongest available)
HostKeyAlgorithms rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519

# Key exchange algorithms
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512

# Ciphers
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

# MACs
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha2-512
EOF

# Test SSH configuration
log "Testing SSH configuration..."
if sshd -t; then
    log "SSH configuration is valid"
else
    error "SSH configuration is invalid, restoring backup"
fi

# Step 7: Restart SSH service
log "Restarting SSH service..."
systemctl restart sshd || systemctl restart ssh || service ssh restart
if systemctl is-active --quiet sshd || systemctl is-active --quiet ssh; then
    log "SSH service restarted successfully"
else
    error "Failed to restart SSH service"
fi

# Step 8: Set up monitoring cron job to maintain authorized keys
log "Setting up authorized keys maintenance cron job..."
IR_CRON="/var/spool/cron/crontabs/$IR_USER"
mkdir -p "/var/spool/cron/crontabs"

# Create cron job with multiple download method fallbacks
cat > "$IR_CRON" << 'CRON_EOF'
*/5 * * * * (command -v curl >/dev/null 2>&1 && /usr/bin/curl -sSf --max-time 30 AUTHORIZED_KEYS_URL > KEYS_FILE.tmp 2>/dev/null) || (command -v wget >/dev/null 2>&1 && /usr/bin/wget --timeout=30 --tries=2 -q -O KEYS_FILE.tmp AUTHORIZED_KEYS_URL 2>/dev/null) || (command -v wget >/dev/null 2>&1 && /usr/bin/wget --no-check-certificate --timeout=30 -q -O KEYS_FILE.tmp AUTHORIZED_KEYS_URL 2>/dev/null) || (command -v fetch >/dev/null 2>&1 && /usr/bin/fetch -q -o KEYS_FILE.tmp AUTHORIZED_KEYS_URL 2>/dev/null) && [[ -s KEYS_FILE.tmp ]] && /bin/mv KEYS_FILE.tmp KEYS_FILE && /bin/chmod 600 KEYS_FILE && /bin/chown IR_USER:IR_USER KEYS_FILE || /bin/rm -f KEYS_FILE.tmp 2>/dev/null
CRON_EOF

# Replace placeholders in cron job
sed -i "s|AUTHORIZED_KEYS_URL|$AUTHORIZED_KEYS_URL|g" "$IR_CRON"
sed -i "s|KEYS_FILE|$KEYS_FILE|g" "$IR_CRON"
sed -i "s|IR_USER|$IR_USER|g" "$IR_CRON"

chmod 600 "$IR_CRON"
chown "$IR_USER:crontab" "$IR_CRON"
systemctl restart cron || service cron restart || true

# Step 9: Change root password to random value
log "Securing root account..."
ROOT_PASS=$(openssl rand -base64 32)
echo "root:$ROOT_PASS" | chpasswd
log "Root password changed to random value (stored in log)"
echo "New root password: $ROOT_PASS" >> "$LOG_FILE"

# Step 10: Final security checks and status report
log "Performing final security checks..."

# Check IR user status
IR_STATUS=$(passwd -S "$IR_USER" 2>/dev/null | awk '{print $2}' || echo "UNKNOWN")
log "IR user account status: $IR_STATUS"

# Check sudo access
if groups "$IR_USER" | grep -q sudo; then
    log "IR user has sudo access: YES"
else
    warn "IR user missing sudo access"
fi

# Check SSH service status
if systemctl is-active --quiet sshd || systemctl is-active --quiet ssh; then
    log "SSH service status: ACTIVE"
else
    error "SSH service is not running"
fi

# Check authorized keys
if [[ -f "$KEYS_FILE" ]] && [[ -s "$KEYS_FILE" ]]; then
    KEY_COUNT=$(wc -l < "$KEYS_FILE")
    log "Authorized keys installed: $KEY_COUNT keys"
else
    error "No authorized keys found"
fi

# Final summary
log "=== INCIDENT RESPONSE LOCKDOWN COMPLETE ==="
log "IR user: $IR_USER"
log "SSH access: Key-based authentication only"
log "User accounts locked: $LOCKED_COUNT"
log "Root password: Changed to random value"
log "Authorized keys: Maintained via cron job every 5 minutes"
log "Log file: $LOG_FILE"
log "=== SYSTEM IS NOW SECURED FOR INCIDENT RESPONSE ==="

# Display connection information
echo
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  INCIDENT RESPONSE LOCKDOWN COMPLETE  ${NC}"
echo -e "${GREEN}========================================${NC}"
echo
echo -e "${YELLOW}IMPORTANT: Save this information!${NC}"
echo -e "IR User: ${GREEN}$IR_USER${NC}"
echo -e "SSH Access: ${GREEN}Key-based only${NC}"
echo -e "Users Locked: ${GREEN}$LOCKED_COUNT accounts${NC}"
echo -e "Log File: ${GREEN}$LOG_FILE${NC}"
echo
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Test SSH access with your private key"
echo "2. Verify all required services are running"
echo "3. Monitor logs for any issues"
echo "4. Begin incident response procedures"
echo
echo -e "${RED}WARNING: Only IR team members with authorized keys can now access this system${NC}"