Hardening de Servidores Linux
$ índice
Cada capa asume que la anterior puede fallar.
1. Actualizaciones y gestión de paquetes
El vector de ataque más común son las vulnerabilidades conocidas con parche disponible.
# Debian/Ubuntu — actualización completa
apt update && apt upgrade -y && apt autoremove -y
# Activar actualizaciones de seguridad automáticas
apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades
Configura el alcance en /etc/apt/apt.conf.d/50unattended-upgrades:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Mail "admin@empresa.com";
⚠️ Activa solo actualizaciones de seguridad de forma automática. Las de funcionalidad pueden romper dependencias — planifícalas manualmente con ventanas de mantenimiento.
2. Hardening de SSH
SSH es la puerta principal a tu servidor. Es también el objetivo número uno de ataques de fuerza bruta. Endurecerlo es obligatorio.
Configuración recomendada
Edita /etc/ssh/sshd_config:
# --- Autenticación ---
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30
# --- Protocolo y cifrado ---
Protocol 2
KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512
# --- Restricciones adicionales ---
Port 2222
AllowUsers deploy oscar
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowTcpForwarding no
Banner /etc/ssh/banner.txt
# --- SFTP interno ---
Subsystem sftp internal-sftp
Genera y gestiona tus claves
# Genera clave Ed25519 (recomendada sobre RSA 4096)
ssh-keygen -t ed25519 -C "deploy@empresa.com" -f ~/.ssh/id_ed25519
# Copia la clave pública al servidor
ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 deploy@servidor
# Verifica permisos correctos
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys
Banner de aviso legal
Crea /etc/ssh/banner.txt:
+------------------------------------------------------+
| SISTEMA PRIVADO -- ACCESO RESTRINGIDO |
| Toda actividad es monitorizada y registrada. |
| El acceso no autorizado es un delito penal. |
+------------------------------------------------------+
# Valida y aplica cambios
sshd -t && systemctl reload sshd
3. Firewall con UFW / nftables
UFW (recomendado para la mayoría de casos)
apt install ufw
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp comment "SSH personalizado"
ufw allow 80/tcp comment "HTTP"
ufw allow 443/tcp comment "HTTPS"
ufw limit 2222/tcp
ufw enable
ufw status verbose
Reglas avanzadas con nftables
#!/usr/sbin/nft -f
# /etc/nftables.conf
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
iifname "lo" accept
ip protocol icmp limit rate 10/second accept
ip6 nexthdr icmpv6 limit rate 10/second accept
ip saddr 192.168.1.0/24 tcp dport 2222 accept
tcp dport { 80, 443 } accept
log prefix "nftables-drop: " drop
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
systemctl enable nftables && systemctl start nftables
4. Fail2Ban — Bloqueo automático de atacantes
apt install fail2ban
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Edita /etc/fail2ban/jail.local:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
banaction = ufw
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24
[sshd]
enabled = true
port = 2222
logpath = %(sshd_log)s
maxretry = 3
bantime = 86400
[nginx-http-auth]
enabled = true
[nginx-limit-req]
enabled = true
# Estado en tiempo real
fail2ban-client status
fail2ban-client status sshd
# Desbanear una IP manualmente
fail2ban-client set sshd unbanip 1.2.3.4
5. Gestión segura de usuarios y privilegios
# Usuario sin shell para servicios
useradd --system --no-create-home --shell /usr/sbin/nologin appuser
# Usuario de deploy con sudo restringido
useradd -m -s /bin/bash deploy
usermod -aG sudo deploy
# Bloquear cuenta root
passwd -l root
Edita /etc/sudoers.d/deploy con visudo -f /etc/sudoers.d/deploy:
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, \
/usr/bin/systemctl reload nginx, \
/usr/bin/certbot renew
deploy ALL=(ALL) PASSWD: ALL
Defaults log_output
Auditoría de cuentas
# Usuarios con shell válida
grep -v '/nologin\|/false' /etc/passwd
# Usuarios con UID 0 (solo debe ser root)
awk -F: '($3 == 0) {print}' /etc/passwd
# Cuentas sin contraseña (CRÍTICO)
awk -F: '($2 == "" || $2 == "!") {print $1}' /etc/shadow
# Últimos logins
lastlog | grep -v "Never"
last | head -20
6. Permisos y ficheros críticos
# Permisos correctos
chmod 640 /etc/shadow
chmod 644 /etc/passwd
chmod 600 /etc/ssh/sshd_config
chmod 700 /root
# Buscar ficheros SUID/SGID
find / -perm /4000 -o -perm /2000 2>/dev/null | sort
# Ficheros world-writable
find / -not \( -path /proc -prune \) -not \( -path /sys -prune \) \
-perm -002 -type f 2>/dev/null
# Inmutabilidad en ficheros críticos
chattr +i /etc/passwd /etc/shadow /etc/sudoers
lsattr /etc/passwd
7. Auditoría con auditd
apt install auditd audispd-plugins
systemctl enable auditd && systemctl start auditd
Añade reglas en /etc/audit/rules.d/hardening.rules:
-D
-b 8192
-f 2
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudo_changes
-w /etc/ssh/sshd_config -p wa -k sshd_config
-w /usr/bin/sudo -p x -k privilege_escalation
-w /bin/su -p x -k privilege_escalation
-w /usr/bin/wget -p x -k download_tools
-w /usr/bin/curl -p x -k download_tools
-w /usr/bin/nc -p x -k netcat
-a always,exit -F arch=b64 -S execve -k exec_commands
-e 2
augenrules --load
ausearch -k identity --start today
ausearch -k sudo_changes -i
aureport --auth --summary
aureport --failed
8. SELinux / AppArmor — Control de acceso obligatorio
AppArmor (Debian/Ubuntu)
aa-status
aa-enforce /etc/apparmor.d/*
journalctl -f | grep apparmor
aa-genprof /usr/bin/mi_app
SELinux (RHEL/CentOS/Rocky)
sestatus
getenforce
setenforce 1
sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config
ausearch -m avc --start recent
sealert -a /var/log/audit/audit.log
ls -Z /var/www/html/
restorecon -Rv /var/www/html/
9. Herramientas de detección de intrusos
Lynis — Auditoría completa del sistema
apt install lynis
lynis audit system
cat /var/log/lynis.log | grep "Suggestion\|Warning"
AIDE — Detección de cambios en ficheros
apt install aide
aideinit
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
echo "0 3 * * * root /usr/bin/aide --check >> /var/log/aide.log 2>&1" \
>> /etc/cron.d/aide
Chkrootkit + Rkhunter
apt install chkrootkit rkhunter
chkrootkit
rkhunter --update
rkhunter --check --sk
echo "0 4 * * 0 root rkhunter --check --sk >> /var/log/rkhunter.log 2>&1" \
>> /etc/cron.d/rkhunter
10. Hardening del kernel con sysctl
Edita /etc/sysctl.d/99-hardening.conf:
# Red
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 2
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.log_martians = 1
# Kernel
kernel.sysrq = 0
kernel.dmesg_restrict = 1
kernel.yama.ptrace_scope = 1
kernel.randomize_va_space = 2
kernel.kptr_restrict = 2
sysctl --system
sysctl net.ipv4.tcp_syncookies # Verificar
11. Script de hardening automatizado
#!/usr/bin/env bash
# =============================================================================
# hardening_baseline.sh — Hardening básico automatizado
# Uso: sudo bash hardening_baseline.sh
# =============================================================================
set -euo pipefail
IFS=$'\n\t'
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
log() { echo -e "${GREEN}[✓]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
err() { echo -e "${RED}[✗]${NC} $*"; }
echo -e "${CYAN}"
cat << 'BANNER'
_ _ _ _
| | | | __ _ _ __ __| | ___ _ __ (_)_ __ __ _
| |_| |/ _` | '__/ _` |/ _ \ '_ \| | '_ \ / _` |
| _ | (_| | | | (_| | __/ | | | | | | | (_| |
|_| |_|\__,_|_| \__,_|\___|_| |_|_|_| |_|\__, |
|___/
BANNER
echo -e "${NC}${BOLD} Linux Baseline Hardening Script v1.0${NC}\n"
[[ $EUID -ne 0 ]] && { err "Ejecutar como root"; exit 1; }
log "Actualizando paquetes..."
apt-get update -qq && apt-get upgrade -y -qq
log "Instalando herramientas de seguridad..."
apt-get install -y -qq ufw fail2ban auditd aide \
unattended-upgrades lynis rkhunter chkrootkit
log "Configurando UFW..."
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp
ufw limit 2222/tcp
ufw --force enable
log "Aplicando parámetros del kernel..."
cat > /etc/sysctl.d/99-hardening.conf << 'EOF'
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.all.rp_filter = 1
kernel.randomize_va_space = 2
kernel.dmesg_restrict = 1
kernel.sysrq = 0
kernel.kptr_restrict = 2
EOF
sysctl --system -q
log "Configurando SSH..."
sed -i 's/^#*PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^#*MaxAuthTries.*/MaxAuthTries 3/' /etc/ssh/sshd_config
sed -i 's/^#*X11Forwarding.*/X11Forwarding no/' /etc/ssh/sshd_config
sshd -t && systemctl reload ssh
log "Configurando Fail2Ban..."
systemctl enable fail2ban --now
log "Inicializando base de datos AIDE..."
aideinit > /dev/null 2>&1
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db 2>/dev/null || true
log "Activando auditd..."
systemctl enable auditd --now
log "Ejecutando auditoría Lynis..."
lynis audit system --quiet 2>/dev/null | grep "Hardening index" || true
echo -e "\n${GREEN}${BOLD}Hardening baseline completado.${NC}"
warn "Ejecuta 'lynis audit system' para recomendaciones adicionales."
Checklist de hardening
Sistema base
- Sistema actualizado con auto-updates de seguridad activos
- Paquetes innecesarios eliminados
Acceso y autenticación
- Login root por SSH desactivado
- Autenticación por contraseña SSH desactivada
- Claves Ed25519 en uso
- Usuarios con mínimo privilegio necesario
- Cuentas de servicio sin shell (
/usr/sbin/nologin)
Red y firewall
- UFW/nftables activo con política
deny all - Solo puertos estrictamente necesarios abiertos
- Fail2Ban activo con reglas SSH y web server
Kernel y sistema
- Parámetros sysctl de hardening aplicados
- AppArmor/SELinux en modo enforcing
- ASLR activado (
randomize_va_space = 2)
Monitorización y auditoría
- auditd activo con reglas para ficheros críticos
- AIDE inicializado con verificación diaria en cron
- Rkhunter/Chkrootkit en cron semanal
- Lynis ejecutado con puntuación > 70
¿Aplicas alguna medida adicional en tu entorno? Compártela en los comentarios.
comentarios(0)
$ dejar comentario