DenyHosts: bloquear intentos fallidos

Todos sufrimos con más frecuencia de lo deseado intentos de ataques por fuerza bruta en los servicios que ofrecen nuestras máquinas, es inevitable. Pero con herramientas como DenyHosts podremos controlar mucho mejor estos intentos de violación.

Su instalación y posterior configuración son triviales, tan solo debemos comprobar que tenemos python instalado en el sistema y poco más:

# dpkg --list | grep python2
ii  python2.5...
# python -V
Python 2.5.2
# apt-get install denyhosts

Una vez instalado pasamos a configurar el archivo /etc/denyhosts.conf, que es el que tiene toda la chicha: [@MORE@]

##### THESE SETTINGS ARE REQUIRED #####
SECURE_LOG = /var/log/auth.log
HOSTS_DENY = /etc/hosts.deny
PURGE_DENY = 1w
BLOCK_SERVICE = ALL
DENY_THRESHOLD_INVALID = 3
DENY_THRESHOLD_VALID = 3
DENY_THRESHOLD_ROOT = 2
DENY_THRESHOLD_RESTRICTED = 2
WORK_DIR = /home/sec/denyhosts
SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES
HOSTNAME_LOOKUP=YES
LOCK_FILE = /var/run/denyhosts.pid
 
##### THESE SETTINGS ARE OPTIONAL #####
ADMIN_EMAIL = r0sk10@gmail.com
SMTP_HOST = localhost
SMTP_PORT = 25
#SMTP_USERNAME=foo
#SMTP_PASSWORD=bar
SMTP_FROM = DenyHosts 
SMTP_SUBJECT = DenyHosts Report
SYSLOG_REPORT=YES
 
AGE_RESET_VALID=5d
AGE_RESET_ROOT=25d
AGE_RESET_RESTRICTED=25d
AGE_RESET_INVALID=10d
 
##### THESE SETTINGS ARE SPECIFIC TO DAEMON MODE #####
DAEMON_LOG = /home/sec/denyhosts/denyhosts.log
DAEMON_SLEEP = 30s
DAEMON_PURGE = 1h

Ajustando las rutas a nuestras necesidades y poco más, reiniciamos el servicio y listo, ya tenemos la máquina protegida contra ataques de fuerza bruta:

# /etc/init.d/denyhosts restart
Restarting DenyHosts (warning).
Stopping DenyHosts: denyhosts.
Starting DenyHosts: denyhosts.
Done (warning).

Ojo: Si queremos poner algún host -o segmento de red- como excepción tan solo tenemos que agregarlo al archivo /etc/hosts.allow indicando el protocolo (ALL para todos) y poco más, por ejemplo:

# cat /etc/hosts.allow
sshd: 10.0.0.255
ALL: 91.34.22.14

Referencias

Ahora si, como siempre, mencionar las buenas referencias de las que hemos tomado nota para la elaboración de esta pequeña receta:

Fail2ban

Viendo el comentario de @igayoso he leido un poco más sobre fail2ban y tenía que probarlo. Me gusta la idea de que filtre vía iptables y no por el /etc/hosts.deny así que ambos (denyhosts y fail2ban) van a convivir por un tiempo, a ver qué tal se llevan.

La instalación y configuración de fail2ban sigue siendo igual de sencilla:

# apt-get install fail2ban
# nano /etc/fail2ban/fail2ban.conf
[Definition]
loglevel = 3
logtarget = /home/sec/fail2ban.log
socket = /var/run/fail2ban/fail2ban.sock
# nano /etc/fail2ban/jail.conf
[DEFAULT]
ignoreip = 127.0.0.1 10.0.0.255 91.34.22.14
bantime  = 86500
maxretry = 3
backend = polling
destemail = micuenta@gmail.com
 
# ACTIONS
banaction = iptables-multiport
mta = sendmail
protocol = tcp
 
action = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s]
               %(mta)s-whois-lines[name=%(__name__)s, dest=\"%(destemail)s\", logpath=%(logpath)s]
 
[ssh]
enabled = true
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
maxretry = 6
 
[pam-generic]
enabled = false
filter  = pam-generic
port = all
banaction = iptables-allports
port     = anyport
logpath  = /var/log/auth.log
maxretry = 6
 
[ssh-ddos]
enabled = false
port    = ssh
filter  = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 6
 
[apache]
enabled = false
port    = http,https
filter  = apache-auth
logpath = /home/www/*/logs/error.log
maxretry = 6
 [...]

Reiniciamos el servicio y veremos como tenemos una nueva regla iptables que nos indica que todo está funcionando:

# /etc/init.d/fail2ban restart
Restarting authentication failure monitor: fail2ban.
# iptables -L
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
fail2ban-ssh  tcp  --  anywhere             anywhere            multiport dports ssh 

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain fail2ban-ssh (1 references)
target     prot opt source               destination         
RETURN     all  --  anywhere             anywhere

Ahora quien intente pasarse de los 3 intentos tendrá a 2 perros mordiendo el cable de su IP.

Referencias

sysadmin

About the author

Óscar
has doubledaddy super powers, father of Hugo and Nico, husband of Marta, *nix user, Djangonaut and open source passionate.
  • No lo conocía. Yo el que suelo usar es fail2ban o cfs+lfd. Te recomiendo que le eches un vistazo a este último porque tiene un montón de cosas interesante para evitar ataques, port scanning, conexiones simultáneas,e tc...
  • @igayoso he actualizado el post con la instalación / configuración de fail2ban también, me ha gustado que sea basado en iptables, gracias por el apunte.
  • Por si quieres seguir probando otros métodos, yo estoy usando blockhosts que también filtra con iptables entre otros: BlockHosts is a script to record how many times a local system is attacked, based on configurable scanning of system logs for sshd or other services. When a particular IP address exceeds a configured number of failed login attempts, that IP address is blocked using hosts.allow files, or by using null-routing, or by using packet filtering. An email notification facility is also available.
  • No sé decirte, llevo usando temas parecidos y sí... se bloquean ataques por fuerza bruta, pero la tasa de retorno de los atacantes es muy baja (en mis pruebas hace 5 años eran un cutre 10.34%). Como medida proactiva ya se puede configurar el openssh (moderno, eso sí), para que sea sensible a esos ataques. Check the man page! :D
blog comments powered by Disqus