#!/bin/bash
#===============================================================================
#                    DEBIAN 13 VPS HARDENING AUTOMATION SCRIPT
#===============================================================================
# Created: September 10, 2025
# Purpose: Automated security hardening for Debian 13 VPS
# Target: Hostinger VPS srv1002428.hstgr.cloud

set -e  # Exit on any error

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

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

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

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    error "Please run as root (use sudo su -)"
fi

log "Starting Debian 13 VPS Hardening..."
log "Target: thebankofdebbie.giize.com (31.97.57.205)"

#===============================================================================
# PHASE 1: SYSTEM UPDATES AND PACKAGES
#===============================================================================

log "PHASE 1: Updating system packages..."
apt update && apt upgrade -y
apt install -y curl wget git vim htop ufw fail2ban unattended-upgrades apt-listchanges

# Enable automatic security updates
log "Configuring automatic security updates..."
echo unattended-upgrades unattended-upgrades/enable_auto_updates boolean true | debconf-set-selections
dpkg-reconfigure -f noninteractive unattended-upgrades

#===============================================================================
# PHASE 2: USER SETUP AND SSH KEYS
#===============================================================================

log "PHASE 2: Setting up non-root user..."

# Create sysadmin user 
if ! id -u sysadmin > /dev/null 2>&1; then
    useradd -m -s /bin/bash sysadmin
    usermod -aG sudo sysadmin
    log "Created sysadmin user with sudo access"
fi

# Set up SSH directory for sysadmin user
mkdir -p /home/sysadmin/.ssh
chmod 700 /home/sysadmin/.ssh
chown sysadmin:sysadmin /home/sysadmin/.ssh

log "SSH key directory prepared. Add your public key to /home/sysadmin/.ssh/authorized_keys"

#===============================================================================
# PHASE 3: SSH HARDENING
#===============================================================================

log "PHASE 3: Hardening SSH configuration..."

# Backup original SSH config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Create hardened SSH config
cat >> /etc/ssh/sshd_config << 'EOF'

# Security Hardening Configuration - Added by automation script
# Port changed from default 22 for security
Port 2255

# Disable root login - use ubuntu user with sudo instead
PermitRootLogin no

# Authentication settings
PubkeyAuthentication yes
PasswordAuthentication yes
# NOTE: Password auth kept enabled initially - disable after testing keys
AuthorizedKeysFile .ssh/authorized_keys

# Security limits
MaxAuthTries 3
LoginGraceTime 30
MaxStartups 3

# Disable unused authentication methods
ChallengeResponseAuthentication no
UsePAM yes

# Protocol and encryption
Protocol 2
Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,umac-128-etm@openssh.com

# Disable X11 forwarding and other features
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no

# User restrictions - only allow sysadmin user
AllowUsers sysadmin

# Banner
Banner /etc/ssh/ssh-banner
EOF

# Create SSH banner
cat > /etc/ssh/ssh-banner << 'EOF'
================================================================================
                             AUTHORIZED ACCESS ONLY
================================================================================
This system is for authorized users only. Activities on this system are 
monitored and recorded. By accessing this system, you acknowledge that your
activities may be monitored for security and administrative purposes.

Unauthorized access is prohibited and punishable by law.
================================================================================
EOF

# Test SSH config
sshd -t || error "SSH configuration has syntax errors"

# Disable SSH socket (systemd) to use our custom port
systemctl disable ssh.socket 2>/dev/null || true
systemctl stop ssh.socket 2>/dev/null || true

log "SSH configuration updated. NEW PORT: 2255"
warn "IMPORTANT: Test SSH key access on port 2255 before disconnecting!"

#===============================================================================
# PHASE 4: FIREWALL CONFIGURATION
#===============================================================================

log "PHASE 4: Configuring UFW firewall..."

# Reset UFW to defaults
ufw --force reset

# Set default policies
ufw default deny incoming
ufw default allow outgoing

# Allow new SSH port
ufw allow 2255/tcp comment "SSH-Hardened"

# Allow web traffic for BTCPay
ufw allow 80/tcp comment "HTTP-BTCPay"
ufw allow 443/tcp comment "HTTPS-BTCPay"

# Allow Tor for local connections
ufw allow from 127.0.0.0/8 to any port 9050 comment "Tor-Local"

# Enable firewall
ufw --force enable

log "UFW firewall configured and enabled"

#===============================================================================
# PHASE 5: FAIL2BAN CONFIGURATION
#===============================================================================

log "PHASE 5: Configuring Fail2Ban..."

cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
# Ban time: 1 hour
bantime = 3600

# Time window for counting failures: 10 minutes  
findtime = 600

# Maximum retry attempts before ban
maxretry = 3

# Log level
loglevel = INFO

[sshd]
enabled = true
port = 2255
filter = sshd
backend = systemd
bantime = 7200
maxretry = 3

[nginx-http-auth]
enabled = true
port = 80,443
filter = nginx-http-auth
logpath = /var/log/nginx/error.log

[nginx-noscript]
enabled = true
port = 80,443
filter = nginx-noscript
logpath = /var/log/nginx/access.log

[nginx-badbots]
enabled = true
port = 80,443
filter = nginx-badbots  
logpath = /var/log/nginx/access.log
maxretry = 2
EOF

systemctl enable fail2ban
systemctl restart fail2ban

log "Fail2Ban configured for SSH and web protection"

#===============================================================================
# PHASE 6: DOCKER INSTALLATION
#===============================================================================

log "PHASE 6: Installing Docker..."

# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
rm get-docker.sh

# Add sysadmin user to docker group
usermod -aG docker sysadmin

# Start and enable Docker
systemctl start docker
systemctl enable docker

log "Docker installed and configured"

#===============================================================================
# PHASE 7: RESTART SSH WITH NEW CONFIGURATION
#===============================================================================

log "PHASE 7: Restarting SSH service..."
systemctl restart ssh

log "SSH restarted on port 2255"

#===============================================================================
# COMPLETION
#===============================================================================

log "==================================================================="
log "DEBIAN 13 VPS HARDENING COMPLETED SUCCESSFULLY!"
log "==================================================================="
log ""
log "CRITICAL NEXT STEPS:"
log "1. Test SSH access on port 2255 with your SSH keys"
log "2. Add your public key to /home/ubuntu/.ssh/authorized_keys"
log "3. Test: ssh -p 2255 ubuntu@srv1002428.hstgr.cloud"
log "4. Once SSH keys work, disable password authentication"
log "5. Run the BTCPay installation script"
log ""
log "SECURITY STATUS:"
log "✅ SSH hardened (port 2255, key auth, root disabled)"
log "✅ UFW firewall active with secure rules"
log "✅ Fail2Ban monitoring intrusions"
log "✅ Automatic security updates enabled"
log "✅ Docker installed and ready"
log ""
warn "DO NOT DISCONNECT until SSH keys are tested on port 2255!"

# Display current status
log "Current system status:"
ufw status numbered
echo ""
systemctl status fail2ban --no-pager -l | head -5
echo ""
docker --version