fbpx Linux Hardening: 10 Security Configs for Server (Guide) | Certificação Linux

Linux Hardening: 10 Essential Security Configurations for Production Servers

📅 07/19/2026 ⏱ 5 min ✍️ Uira Ribeiro
Linux Hardening: 10 Essential Security Configurations for Production Servers
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

A freshly installed Linux server with SSH root enabled and no firewall receives brute force login attempts in less than 5 minutes after getting a public IP. This guide covers the minimum settings every production server should have.

1. Create Non-Root User and Configure sudo

# Criar usuário administrador
sudo adduser deploy

# Adicionar ao grupo sudo (Debian/Ubuntu)
sudo usermod -aG sudo deploy

# Em vez de acesso sudo irrestrito, conceder apenas o necessário
# Editar com visudo (valida sintaxe antes de salvar)
sudo visudo

# Adicionar no final do arquivo /etc/sudoers:
# deploy  ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/apt

2. SSH Key Authentication (Disable Password)

# Na sua máquina local, gerar par de chaves (se não tiver)
ssh-keygen -t ed25519 -C "deploy@meuservidor"

# Copiar chave pública para o servidor
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@SEU_IP

# Testar login com chave antes de desativar senha!
ssh -i ~/.ssh/id_ed25519 deploy@SEU_IP
# No servidor: editar /etc/ssh/sshd_config
sudo nano /etc/ssh/sshd_config
# Configurações de segurança SSH
Port 2222                    # mudar a porta padrão (reduz bots)
PermitRootLogin no           # nunca root direto
PasswordAuthentication no    # somente chaves
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowUsers deploy            # whitelist de usuários
sudo sshd -t          # validar config antes de recarregar
sudo systemctl reload sshd

3. Firewall with UFW

sudo apt install ufw -y

# Política padrão: bloquear tudo que entra, liberar tudo que sai
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Liberar apenas o necessário
sudo ufw allow 2222/tcp comment 'SSH'
sudo ufw allow 80/tcp  comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

# Ativar (confirma com y)
sudo ufw enable

sudo ufw status verbose

4. Fail2ban: Automatic Brute Force Blocking

sudo apt install fail2ban -y

# Criar configuração local (não edite .conf diretamente — será sobrescrita em upgrades)
sudo tee /etc/fail2ban/jail.local <<'EOF'
[DEFAULT]
bantime  = 3600      # banir por 1 hora
findtime = 600       # janela de 10 minutos
maxretry = 5         # máximo de tentativas

[sshd]
enabled = true
port    = 2222       # mesma porta do seu sshd_config
logpath = %(sshd_log)s
backend = %(sshd_backend)s
EOF

sudo systemctl enable --now fail2ban

# Ver IPs banidos
sudo fail2ban-client status sshd

5. Automatic Security Updates

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure --priority=low unattended-upgrades

# Verificar configuração
cat /etc/apt/apt.conf.d/20auto-upgrades
# Deve conter:
# APT::Periodic::Update-Package-Lists "1";
# APT::Periodic::Unattended-Upgrade "1";

6. Disable Unnecessary Services

# Ver serviços ativos
systemctl list-units --type=service --state=active

# Exemplos de serviços para desativar em servidor headless
sudo systemctl disable --now avahi-daemon    # descoberta de rede local
sudo systemctl disable --now cups            # impressão
sudo systemctl disable --now bluetooth       # bluetooth

# Ver portas abertas
ss -tlnp

7. Configure sysctl for Network Hardening

sudo tee /etc/sysctl.d/99-hardening.conf <<'EOF'
# Desativar redirecionamento de pacotes IP (não é roteador)
net.ipv4.ip_forward = 0

# Proteção contra SYN flood
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048

# Ignorar pings de broadcast
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Proteção contra IP spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Não aceitar source routing
net.ipv4.conf.all.accept_source_route = 0

# Desativar magic sysrq (acesso de baixo nível)
kernel.sysrq = 0
EOF

sudo sysctl --system

8. Monitor Logins and Activity with auditd

sudo apt install auditd -y
sudo systemctl enable --now auditd

# Regras básicas de auditoria
sudo tee /etc/audit/rules.d/hardening.rules <<'EOF'
# Monitorar logins
-w /var/log/auth.log -p wa -k auth

# Monitorar mudanças em arquivos críticos
-w /etc/passwd   -p wa -k identity
-w /etc/shadow   -p wa -k identity
-w /etc/sudoers  -p wa -k privilege_escalation
-w /etc/ssh/sshd_config -p wa -k sshd

# Monitorar execução de comandos privilegiados
-a always,exit -F arch=b64 -S execve -F euid=0 -k root_commands
EOF

sudo augenrules --load

# Consultar eventos
sudo ausearch -k sshd
sudo ausearch -k privilege_escalation

9. Critical File Permissions

# Verificar arquivos com SUID/SGID (revisar periodicamente)
find / -perm /4000 -o -perm /2000 2>/dev/null | grep -v proc

# Proteger arquivos de senha
sudo chmod 640 /etc/shadow
sudo chmod 644 /etc/passwd

# Remover SUID de binários não essenciais (com cuidado)
# sudo chmod u-s /usr/bin/at    # se não usar at jobs

# Arquivos sem dono são risco — encontrar e corrigir
sudo find / -nouser -o -nogroup 2>/dev/null | grep -v proc

10. Quick Checklist Before Going to Production

  • ✅ Non-root user created and tested
  • ✅ SSH on alternate port, root disabled, password disabled
  • ✅ SSH key login tested (before closing the current session!)
  • ✅ UFW active — only necessary ports open
  • ✅ Fail2ban configured and active
  • ✅ Automatic security updates enabled
  • ✅ Unnecessary services disabled
  • ✅ Network sysctl applied
  • ✅ auditd running with basic rules
  • ✅ Backup tested and restoration verified

Hardening and Linux Certification

Linux server security is covered in LPIC-2 (topic 212) and CompTIA Linux+ (Security domain). But more than passing the exam, applying hardening in real environments is what distinguishes a sysadmin who "makes it work" from one who "makes it work securely" — and this is what SRE and DevOps jobs require.

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp