#!/bin/bash
# ============================================================
# Ubuntu Server Security Hardening
# Run ONCE after install.sh: sudo bash server_hardening.sh
# ============================================================
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; BLUE='\033[0;34m'; NC='\033[0m'
log()  { echo -e "${GREEN}[✓]${NC} $1"; }
info() { echo -e "${BLUE}[→]${NC} $1"; }

[[ $EUID -ne 0 ]] && echo -e "${RED}[✗]${NC} Run as root" && exit 1

# ── SSH Hardening ────────────────────────────────────────────
info "Hardening SSH..."
SSH_CONFIG="/etc/ssh/sshd_config.d/99-cryptomining.conf"
cat > "${SSH_CONFIG}" <<SSH
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 30
X11Forwarding no
AllowTcpForwarding no
SSH
systemctl reload ssh 2>/dev/null || systemctl reload sshd
log "SSH hardened (root login disabled, password auth disabled)"

# ── Fail2Ban ─────────────────────────────────────────────────
info "Configuring fail2ban..."
cat > /etc/fail2ban/jail.local <<F2B
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
backend  = systemd

[sshd]
enabled  = true
maxretry = 3
bantime  = 24h

[nginx-http-auth]
enabled  = true

[nginx-limit-req]
enabled  = true
filter   = nginx-limit-req
logpath  = /var/log/nginx/cryptomining_error.log
maxretry = 10
F2B

systemctl enable --now fail2ban
log "Fail2ban configured"

# ── Sysctl Security ──────────────────────────────────────────
info "Applying kernel security settings..."
cat > /etc/sysctl.d/99-cryptomining.conf <<SYSCTL
# Disable IP forwarding
net.ipv4.ip_forward = 0

# SYN flood protection
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2

# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0

# Ignore ICMP broadcasts
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
SYSCTL
sysctl -p /etc/sysctl.d/99-cryptomining.conf &>/dev/null
log "Kernel security settings applied"

# ── Automatic Security Updates ───────────────────────────────
info "Enabling automatic security updates..."
apt-get install -y -qq unattended-upgrades
cat > /etc/apt/apt.conf.d/20auto-upgrades <<AUTO
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
AUTO
log "Auto security updates enabled"

# ── MySQL Hardening ──────────────────────────────────────────
info "Hardening MySQL..."
cat > /etc/mysql/conf.d/cryptomining_security.cnf <<MYSQL_CNF
[mysqld]
# Disable remote root login
skip-networking = 0
bind-address = 127.0.0.1

# Logging
general_log = 0
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

# Security
local-infile = 0
MYSQL_CNF
systemctl restart mysql
log "MySQL bound to localhost only"

echo ""
log "Server hardening complete!"
echo ""
echo -e "${BLUE}Important reminders:${NC}"
echo "  • Copy your SSH public key before disabling password auth:"
echo "    ssh-copy-id user@server"
echo "  • Check fail2ban status: sudo fail2ban-client status"
echo "  • Check banned IPs:      sudo fail2ban-client status sshd"
