Checklist de hardening Ubuntu VPS

    Provisionar um VPS sem hardening é como instalar uma fechadura moderna numa porta sem paredes. Este checklist cobre todos os controles essenciais — da configuração inicial do SSH ao monitoramento contínuo — para transformar um servidor Ubuntu recém-criado em uma máquina pronta para rodar aplicações de produção com segurança.

    Fase 1: acesso e autenticação

    Primeiros passos logo após provisionar o VPS:

    bash
    # ── FASE 1: Acesso seguro ──────────────────────────────────────────
    
    # [1.1] Criar usuário não-root para operações cotidianas:
    adduser deploy
    usermod -aG sudo deploy
    
    # [1.2] Instalar chave SSH para o novo usuário:
    mkdir -p /home/deploy/.ssh
    curl https://github.com/SEU_USUARIO.keys >> /home/deploy/.ssh/authorized_keys
    chmod 700 /home/deploy/.ssh && chmod 600 /home/deploy/.ssh/authorized_keys
    chown -R deploy:deploy /home/deploy/.ssh
    
    # [1.3] Hardening do SSH (/etc/ssh/sshd_config.d/hardening.conf):
    cat > /etc/ssh/sshd_config.d/hardening.conf << 'EOF'
    PasswordAuthentication no
    PermitRootLogin no
    AllowUsers deploy
    MaxAuthTries 3
    X11Forwarding no
    AllowAgentForwarding no
    ClientAliveInterval 300
    ClientAliveCountMax 3
    EOF
    sshd -t && systemctl reload ssh
    
    # [1.4] Testar novo acesso ANTES de fechar sessão atual:
    # Em NOVO terminal: ssh deploy@IP_VPS
    # Confirmar login sem senha funciona
    
    # [1.5] Verificar:
    # ✅ Login como deploy funciona com chave
    # ✅ Login como root negado
    # ✅ Login por senha negado

    Fase 2: firewall e rede

    Configurar UFW e parâmetros de rede seguros:

    bash
    # ── FASE 2: Firewall ───────────────────────────────────────────────
    
    # [2.1] Configurar UFW:
    ufw default deny incoming
    ufw default allow outgoing
    ufw allow ssh       # ou porta customizada: ufw allow 2222/tcp
    ufw allow http
    ufw allow https
    ufw enable
    
    # [2.2] Parâmetros de kernel de rede:
    tee /etc/sysctl.d/99-security.conf << 'EOF'
    net.ipv4.tcp_syncookies = 1
    net.ipv4.conf.all.rp_filter = 1
    net.ipv4.conf.all.accept_redirects = 0
    net.ipv4.conf.all.send_redirects = 0
    net.ipv4.icmp_echo_ignore_broadcasts = 1
    kernel.randomize_va_space = 2
    kernel.dmesg_restrict = 1
    EOF
    sysctl --system
    
    # [2.3] Verificar portas abertas:
    ss -tlnp  # apenas ssh(22), nginx(80/443) devem estar abertas ao mundo
    
    # [2.4] Verificar:
    # ✅ UFW ativo: ufw status verbose
    # ✅ Apenas portas necessárias abertas
    # ✅ PostgreSQL/Redis NÃO acessíveis externamente

    Fase 3: atualizações e serviços

    Manter o sistema atualizado e remover o desnecessário:

    bash
    # ── FASE 3: Atualizações e serviços ───────────────────────────────
    
    # [3.1] Atualizar sistema imediatamente:
    apt update && apt upgrade -y && apt autoremove -y
    
    # [3.2] Habilitar atualizações automáticas de segurança:
    apt install unattended-upgrades
    dpkg-reconfigure --priority=low unattended-upgrades
    
    # Configurar em /etc/apt/apt.conf.d/50unattended-upgrades:
    sed -i 's|//.*"${distro_id}:${distro_codename}-security";|"${distro_id}:${distro_codename}-security";|'   /etc/apt/apt.conf.d/50unattended-upgrades
    
    # [3.3] Desabilitar serviços desnecessários:
    for svc in avahi-daemon cups bluetooth whoopsie; do
      systemctl disable --now $svc 2>/dev/null || true
    done
    
    # [3.4] Remover pacotes não necessários:
    apt remove --purge telnet ftp rsh-client   nis rpcbind nfs-kernel-server 2>/dev/null || true
    
    # [3.5] Verificar serviços rodando:
    systemctl list-units --type=service --state=running
    
    # Verificar:
    # ✅ Sistema atualizado: apt list --upgradable
    # ✅ unattended-upgrades ativo: systemctl status unattended-upgrades
    # ✅ Sem serviços desnecessários rodando

    Fase 4: detecção e auditoria

    Instalar ferramentas de detecção de intrusão e auditoria:

    bash
    # ── FASE 4: Detecção e auditoria ──────────────────────────────────
    
    # [4.1] Fail2ban:
    apt install fail2ban
    tee /etc/fail2ban/jail.local << 'EOF'
    [DEFAULT]
    bantime  = 1h
    findtime = 10m
    maxretry = 5
    banaction = ufw
    
    [sshd]
    enabled  = true
    maxretry = 3
    bantime  = 24h
    EOF
    systemctl enable --now fail2ban
    
    # [4.2] rkhunter + chkrootkit:
    apt install rkhunter chkrootkit
    rkhunter --update && rkhunter --propupd
    rkhunter --check --sk --rwo
    
    # [4.3] auditd:
    apt install auditd
    tee /etc/audit/rules.d/hardening.rules << 'EOF'
    -D
    -b 8192
    -w /etc/passwd -p rwxa -k identity
    -w /etc/shadow -p rwxa -k identity
    -w /etc/sudoers -p rwa -k sudo-config
    -w /etc/ssh/sshd_config -p rwxa -k ssh-config
    -a always,exit -F arch=b64 -S execve -F euid=0 -k root-commands
    -e 2
    EOF
    augenrules --load
    systemctl enable --now auditd
    
    # [4.4] Lynis (score de segurança):
    apt install lynis
    lynis audit system --quick 2>/dev/null
    lynis_score=$(grep "hardening_index" /var/log/lynis-report.dat | cut -d= -f2)
    echo "Score Lynis: $lynis_score"

    Fase 5: monitoramento contínuo e resposta

    Script de verificação semanal e procedimento de resposta:

    bash
    # ── FASE 5: Monitoramento contínuo ────────────────────────────────
    
    # [5.1] Script de verificação semanal:
    tee /usr/local/bin/security-check.sh << 'SCRIPT'
    #!/bin/bash
    echo "=== Security Check $(date) ===" >> /var/log/security-check.log
    
    # Verificar atualizações pendentes:
    UPDATES=$(apt list --upgradable 2>/dev/null | grep -c "upgradable")
    echo "Atualizações pendentes: $UPDATES" >> /var/log/security-check.log
    
    # Verificar IPs banidos pelo Fail2ban:
    BANNED=$(fail2ban-client status sshd | grep "Currently banned" | awk '{print $NF}')
    echo "IPs banidos (SSH): $BANNED" >> /var/log/security-check.log
    
    # Verificar score Lynis:
    lynis audit system --quick 2>/dev/null
    SCORE=$(grep "hardening_index" /var/log/lynis-report.dat | cut -d= -f2)
    echo "Score Lynis: $SCORE" >> /var/log/security-check.log
    
    # Alertar se score cair:
    if [ -n "$SCORE" ] && [ "$SCORE" -lt 65 ]; then
      echo "⚠️ Score de segurança baixo: $SCORE" |     mail -s "Alerta segurança: $(hostname)" admin@seudominio.com.br
    fi
    SCRIPT
    chmod +x /usr/local/bin/security-check.sh
    echo "0 6 * * 0 root /usr/local/bin/security-check.sh" | tee /etc/cron.d/security-check
    
    # Checklist final — tudo deve ser ✅:
    echo "✅ SSH sem senha: $(grep -c 'PasswordAuthentication no' /etc/ssh/sshd_config.d/hardening.conf) regra"
    echo "✅ UFW ativo: $(ufw status | grep -c 'Status: active') serviço"
    echo "✅ Fail2ban: $(systemctl is-active fail2ban)"
    echo "✅ auditd: $(systemctl is-active auditd)"
    echo "✅ unattended-upgrades: $(systemctl is-active unattended-upgrades)"
    echo "✅ rkhunter warnings: $(rkhunter --check --sk --rwo 2>&1 | grep -c Warning || echo 0)"

    $ runstack deploy --plan starter

    Não quer configurar manualmente?

    Não quer configurar manualmente? Implante o VPS Linux em menos de 3 minutos com a Runstack. Infraestrutura da OPEN DATACENTER, com servidores no Brasil.

    Perguntas frequentes