#!/bin/bash
# ==========================================================
# 192.168.0.188 (Ollama Server) 安全加固腳本
#
# 使用方式：
#   ssh ollama@192.168.0.188
#   sudo bash harden_ollama_server.sh
# ==========================================================

set -e

echo "=========================================="
echo "  Ollama Server 安全加固腳本"
echo "=========================================="

# 1. 安裝並配置 Fail2Ban
echo ""
echo "=== 1. 安裝 Fail2Ban (SSH 防暴力破解) ==="
apt-get update -qq
apt-get install -y fail2ban

cat > /etc/fail2ban/jail.local << 'JAIL'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
ignoreip = 127.0.0.1/8 192.168.0.0/24

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
JAIL

systemctl enable fail2ban
systemctl restart fail2ban
echo "✅ Fail2Ban 已安裝並啟用"

# 2. 設定 UFW 防火牆
echo ""
echo "=== 2. 設定 UFW 防火牆 ==="
apt-get install -y ufw

# 重置並設定預設規則
ufw --force reset
ufw default deny incoming
ufw default allow outgoing

# 允許必要的服務
ufw allow 22/tcp comment 'SSH'
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'
ufw allow from 192.168.0.0/24 to any port 11434 comment 'Ollama API (內網)'
ufw allow from 192.168.0.0/24 to any port 3000 comment 'Open WebUI (內網)'
ufw allow from 192.168.0.0/24 to any port 5678 comment 'n8n (內網)'
ufw allow from 192.168.0.0/24 to any port 8080 comment 'SearXNG (內網)'

# 啟用防火牆
ufw --force enable
echo "✅ UFW 防火牆已設定"

# 3. 修改 Docker 容器端口綁定 (n8n 改為只允許內網)
echo ""
echo "=== 3. 檢查 Docker Compose 配置 ==="
echo "⚠️  請手動修改 docker-compose.yml 將以下服務改為內網綁定："
echo "    n8n:      5678:5678 → 192.168.0.188:5678:5678"
echo "    searxng:  8080:8080 → 192.168.0.188:8080:8080"

# 4. 顯示最終狀態
echo ""
echo "=========================================="
echo "  安全加固完成！"
echo "=========================================="
echo ""
echo "Fail2Ban 狀態："
fail2ban-client status sshd 2>/dev/null || echo "  (啟動中...)"
echo ""
echo "UFW 防火牆規則："
ufw status verbose
echo ""
echo "⚠️  注意事項："
echo "  1. 外部訪問 Ollama API/n8n/SearXNG 已被限制為內網 (192.168.0.0/24)"
echo "  2. 如需從外部訪問，請透過 Nginx 反向代理並加入認證"
echo "  3. 建議定期檢查 fail2ban-client status sshd"
