Configurando un SSH seguro

Buenas noches, bloggeros.

Bueno, el título del post lo dice todo: todos usamos SSH para algo... por eso es importante tener una configuración apropiada, ya que dejar la configuración by default no es una buena idea.


Hay muchas herramientas que nos ayudan a mantener nuestro servidor SSH a salvo de alguna manera, pero si la configuración del servidor no es la correcta, no nos valdrá de mucho el fail2ban, por ejemplo.

Vamos a lo importante, el fichero /etc/ssh/ssh_config:

# What ports, IPs and protocols we listen for - Lo podemos cambiar
Port 6622
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel VERBOSE

# Authentication:
LoginGraceTime 30
# Tiempo que disponemos para iniciar la sesión antes de que nos desconecte el server
PermitRootLogin no
#I M P O R T A N T E
StrictModes yes
AllowUsers yousuario
# Usuario que puede loguearse

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

#Deshabilitar el servidor X vía SSH
X11Forwarding no
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

MaxStartups 1
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

UsePAM yes
#
MaxAuthTries 3
#Cantidad maxima de intentos de logueo
ClientAliveInterval 300
AllowTcpforwarding no
DebianBanner no
#Ocultar la info de nuestro server si nos escanea nmap 

Lo recomendable, sin embargo sería:
  • loguearnos utilizando clave pública/clave privada
  • indicar la IP desde la que vamos a loguearnos (no siempre es posible)
  • conectarnos al server a través de VPN
A veces debemos exponer nuestro servidor en internet, por lo que vamos a ser víctimas de bots intentando hacerse del server mediante ataque de fuerza bruta. Por eso fail2ban es una herramienta súmamente interesante que nos ayudará a mantener en lista negra, mediante iptables, a todas aquellas IP que hayan provocado intentos fallidos de conexión. 

En Debian y derivados, pueden encontrar a fail2ban en los repositorios e instalarlo mediante el comando

apt-get install fail2ban

Se cambian algunas cositas del fichero /etc/fail2ban/jail.conf (esto sólo es una porción del fichero)

[DEFAULT]

ignoreip = 127.0.0.1/8

ignorecommand =

# "bantime" is the number of seconds that a host is banned.
bantime  = 25200

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime = 60
maxretry = 3

backend = polling

usedns = warn

destemail = root@localhost

sendername = Fail2Ban

sender = fail2ban@localhost

#
# ACTIONS
#

banaction = iptables-multiport

# email action. Since 0.8.1 upstream fail2ban uses sendmail
# MTA for the mailing. Change mta configuration parameter to mail
# if you want to revert to conventional 'mail'.
mta = sendmail

# Default protocol
protocol = tcp

# Specify chain where jumps would need to be added in iptables-* actions
chain = INPUT

#
# Action shortcuts. To be used to define action parameter

# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]

# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
              %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s", sendername="%(sendername)s"]

# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
               %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s", sendername="%(sendername)s"]

# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_)s

#
# JAILS
#

[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3

Y también en /etc/fail2ban/action.d/iptables-blocktype.conf


[INCLUDES]

after = iptables-blocktype.local

[Init]

# Option:  blocktype
# Note:    This is what the action does with rules. This can be any jump target
#          as per the iptables man page (section 8). Common values are DROP
#          REJECT, REJECT --reject-with icmp-port-unreachable
# Values:  STRING
#blocktype = REJECT --reject-with icmp-port-unreachable
blocktype = DROP

para que en vez de hacer un REJECT haga DROP sobre la IP banneada.

Otra capa de seguridad que podemos añadir al servicio es la autenticación de dos pasos y la integración de Latch.

Como lectura adicional, les dejo dos enlaces que me parecen sumamente interesantes relacionados con el tema de este post:
Espero que haya sido de utilidad. No obstante, siempre lo mejor es leer la docu oficial para ajustar la configuración de la mejor manera.

Saludos... y happy config.!

Comentarios

Entradas más populares de este blog

Zabbix en dos días (día 1)

OpenVPN para todos :D

GRUB2 experience