🛡️ Add comprehensive Security Hardening Plan

- Created SECURITY-HARDENING-PLAN.md with 6 security levels
- Added setup-node1-security.sh for automated hardening
- Added scan-image.sh for pre-deployment image scanning
- Created docker-compose.secure.yml template
- Includes: Trivy, fail2ban, UFW, auditd, rkhunter, chkrootkit
- Network isolation, egress filtering, process monitoring
- Incident response procedures and recovery playbook
This commit is contained in:
Apple
2026-01-10 05:05:21 -08:00
parent 1c247ea40c
commit 1231647f94
4 changed files with 1223 additions and 0 deletions

120
scripts/security/scan-image.sh Executable file
View File

@@ -0,0 +1,120 @@
#!/bin/bash
# ============================================================
# scan-image.sh — Сканування Docker образу перед використанням
# ============================================================
# Використання:
# ./scan-image.sh postgres:16-alpine
# ./scan-image.sh --pull postgres:16-alpine
# ============================================================
set -e
# Кольори
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'
# Параметри
PULL=false
IMAGE=""
# Парсинг аргументів
while [[ $# -gt 0 ]]; do
case $1 in
--pull|-p)
PULL=true
shift
;;
*)
IMAGE="$1"
shift
;;
esac
done
if [ -z "$IMAGE" ]; then
echo "Usage: $0 [--pull] <image_name>"
echo "Example: $0 postgres:16-alpine"
echo " $0 --pull postgres:16-alpine"
exit 1
fi
echo -e "${CYAN}🔍 Scanning Docker Image: $IMAGE${NC}"
echo "========================================"
date
echo ""
# Перевірка Trivy
if ! command -v trivy &> /dev/null; then
echo -e "${RED}❌ Trivy not installed!${NC}"
echo "Install: curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin"
exit 1
fi
# Pull якщо потрібно
if [ "$PULL" = true ]; then
echo -e "${YELLOW}📥 Pulling image...${NC}"
docker pull "$IMAGE"
echo ""
fi
# Отримати digest
echo -e "${YELLOW}📋 Image Info:${NC}"
DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' "$IMAGE" 2>/dev/null || echo "N/A")
echo " Digest: $DIGEST"
echo ""
# Сканування на вразливості
echo -e "${YELLOW}🔒 Scanning for vulnerabilities...${NC}"
echo ""
# Запуск Trivy
trivy image --severity HIGH,CRITICAL "$IMAGE"
SCAN_EXIT=$?
echo ""
echo "========================================"
if [ $SCAN_EXIT -eq 0 ]; then
echo -e "${GREEN}✅ No HIGH/CRITICAL vulnerabilities found${NC}"
echo ""
echo -e "${GREEN}Safe to use:${NC}"
echo " image: $IMAGE"
if [ "$DIGEST" != "N/A" ]; then
echo ""
echo -e "${GREEN}Recommended (pinned by digest):${NC}"
echo " image: $DIGEST"
fi
else
echo -e "${RED}❌ Vulnerabilities found!${NC}"
echo ""
echo "Options:"
echo " 1. Use a different image version"
echo " 2. Build custom image with patches"
echo " 3. Accept risk (not recommended)"
exit 1
fi
# Додаткова перевірка на malware
echo ""
echo -e "${YELLOW}🦠 Checking for known malware patterns...${NC}"
# Запустити контейнер і перевірити /tmp
MALWARE_CHECK=$(docker run --rm "$IMAGE" sh -c "ls -la /tmp 2>/dev/null | grep -E '(httpd|\.perf|mysql|xmrig|kdevtmp)' || echo 'clean'" 2>/dev/null || echo "check_failed")
if [ "$MALWARE_CHECK" = "clean" ]; then
echo -e "${GREEN}✅ No known malware patterns in /tmp${NC}"
elif [ "$MALWARE_CHECK" = "check_failed" ]; then
echo -e "${YELLOW}⚠️ Could not check /tmp (image may not have shell)${NC}"
else
echo -e "${RED}❌ MALWARE DETECTED in /tmp!${NC}"
echo "$MALWARE_CHECK"
echo ""
echo -e "${RED}DO NOT USE THIS IMAGE!${NC}"
exit 1
fi
echo ""
echo -e "${GREEN}🎉 Image scan complete!${NC}"

View File

@@ -0,0 +1,195 @@
#!/bin/bash
# ============================================================
# setup-node1-security.sh — Налаштування безпеки NODE1
# ============================================================
# Запускати на NODE1 після rebuild:
# ssh root@144.76.224.179
# bash < <(curl -s https://raw.githubusercontent.com/.../setup-node1-security.sh)
# ============================================================
set -e
echo "🛡️ NODE1 Security Setup"
echo "========================"
date
echo ""
# Кольори
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# 1. Оновлення системи
echo -e "${YELLOW}[1/10] Оновлення системи...${NC}"
apt update && apt upgrade -y
# 2. Встановлення security tools
echo -e "${YELLOW}[2/10] Встановлення security tools...${NC}"
apt install -y \
fail2ban \
ufw \
auditd \
rkhunter \
chkrootkit \
lynis \
aide \
unattended-upgrades \
apt-listchanges
# 3. Встановлення Trivy (image scanner)
echo -e "${YELLOW}[3/10] Встановлення Trivy...${NC}"
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
trivy --version
# 4. Налаштування fail2ban
echo -e "${YELLOW}[4/10] Налаштування fail2ban...${NC}"
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
EOF
systemctl enable fail2ban
systemctl restart fail2ban
# 5. Налаштування UFW (firewall)
echo -e "${YELLOW}[5/10] Налаштування UFW...${NC}"
ufw default deny incoming
ufw default deny outgoing
ufw allow 22/tcp comment 'SSH'
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'
ufw allow out 53/udp comment 'DNS'
ufw allow out 443/tcp comment 'HTTPS out'
ufw allow out 80/tcp comment 'HTTP out'
ufw allow out 123/udp comment 'NTP'
# Block internal networks
ufw deny out to 10.0.0.0/8
ufw deny out to 172.16.0.0/12
echo "y" | ufw enable
# 6. Kernel hardening
echo -e "${YELLOW}[6/10] Kernel hardening...${NC}"
cat >> /etc/sysctl.conf << 'EOF'
# Security hardening
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
kernel.randomize_va_space = 2
EOF
sysctl -p
# 7. Налаштування auditd
echo -e "${YELLOW}[7/10] Налаштування auditd...${NC}"
cat > /etc/audit/rules.d/security.rules << 'EOF'
# Monitor Docker
-w /usr/bin/docker -p rwxa -k docker
-w /var/lib/docker -p rwxa -k docker
-w /etc/docker -p rwxa -k docker
# Monitor /tmp for executables
-w /tmp -p x -k tmp_exec
# Monitor cron
-w /etc/crontab -p wa -k cron
-w /etc/cron.d -p wa -k cron
# Monitor passwd/shadow
-w /etc/passwd -p wa -k passwd
-w /etc/shadow -p wa -k shadow
# Monitor network config
-w /etc/hosts -p wa -k hosts
-w /etc/network -p wa -k network
EOF
systemctl enable auditd
systemctl restart auditd
# 8. Створення директорій
echo -e "${YELLOW}[8/10] Створення директорій...${NC}"
mkdir -p /opt/scripts
mkdir -p /opt/config
mkdir -p /opt/backups
mkdir -p /var/log/security
# 9. Створення security check script
echo -e "${YELLOW}[9/10] Створення security check script...${NC}"
cat > /opt/scripts/security-check.sh << 'SCRIPT'
#!/bin/bash
# Security check script - runs every hour
LOG="/var/log/security/check-$(date +%Y%m%d).log"
echo "$(date) - Starting security check" >> $LOG
# Check for suspicious processes
SUSPICIOUS=$(ps aux | grep -E "(xmrig|kdevtmp|kinsing|perfctl|httpd.*tmp|softirq|vrarhpb)" | grep -v grep)
if [ -n "$SUSPICIOUS" ]; then
echo "🚨 ALERT: Suspicious process found!" >> $LOG
echo "$SUSPICIOUS" >> $LOG
pkill -9 -f "xmrig|kdevtmp|kinsing|perfctl"
fi
# Check /tmp for executables
TMP_EXEC=$(find /tmp -type f -executable 2>/dev/null)
if [ -n "$TMP_EXEC" ]; then
echo "🚨 ALERT: Executable in /tmp!" >> $LOG
echo "$TMP_EXEC" >> $LOG
rm -f $TMP_EXEC
fi
# Check CPU load
LOAD=$(cat /proc/loadavg | cut -d' ' -f1)
if (( $(echo "$LOAD > 5" | bc -l) )); then
echo "⚠️ WARNING: High CPU load: $LOAD" >> $LOG
ps aux --sort=-%cpu | head -10 >> $LOG
fi
# Check for unknown containers
UNKNOWN=$(docker ps --format '{{.Names}}' 2>/dev/null | grep -v -E "^(dagi-|postgres|redis|neo4j|qdrant|grafana|prometheus)")
if [ -n "$UNKNOWN" ]; then
echo "⚠️ WARNING: Unknown containers: $UNKNOWN" >> $LOG
fi
echo "$(date) - Security check complete" >> $LOG
SCRIPT
chmod +x /opt/scripts/security-check.sh
# 10. Налаштування cron
echo -e "${YELLOW}[10/10] Налаштування cron...${NC}"
cat > /etc/cron.d/security << 'EOF'
# Security checks
0 * * * * root /opt/scripts/security-check.sh
0 3 * * * root rkhunter --update && rkhunter --check --skip-keypress > /var/log/security/rkhunter.log 2>&1
0 4 * * * root chkrootkit > /var/log/security/chkrootkit.log 2>&1
EOF
# Фінальна перевірка
echo ""
echo -e "${GREEN}✅ Security setup complete!${NC}"
echo ""
echo "Встановлено:"
echo " ✓ fail2ban (SSH protection)"
echo " ✓ UFW (firewall with egress filtering)"
echo " ✓ Trivy (image scanner)"
echo " ✓ auditd (system auditing)"
echo " ✓ rkhunter + chkrootkit (rootkit detection)"
echo " ✓ Security check script (hourly)"
echo ""
echo "Перевірка:"
echo " ufw status"
echo " fail2ban-client status"
echo " trivy --version"
echo " /opt/scripts/security-check.sh"