[2024-feb-29] Sad news: Eric Layton aka Nocturnal Slacker aka vtel57 passed away on Feb 26th, shortly after hospitalization. He was one of our Wiki's most prominent admins. He will be missed.

Welcome to the Slackware Documentation Project

¡Esta es una revisión vieja del documento!


Mejorando la seguridad de OpenSSH

OpenSSH es la navaja suiza de los programas de acceso remoto: le proporciona un shell en su máquina distante,y transmite datos de forma segura y encriptada - incluyendo comandos, transferencia de archivos, sesiones X11 y VNC, datos rsync, etc.

OpenSSHes tan avanzado que puede considerarse como una VPN simplificada (red privada virtual).

Slackware contiene OpenSSHpor supuesto, y la configuración por defecto ya es bastante segura.Esta página se ha creado para mostrarle algunos ajustes de configuración simples que se pueden aplicar a la configuración predeterminada para mejorar su seguridad.

Necesitará saber cómo usar un editor de texto para poder seguir este HOWTO. Si eres un principiante completo, prueba nano.Una vez que esté más avanzado y más cómodo con Linux, siéntase libre de usar algo más poderoso …

Los archivos de configuración de SSH y encontrar más información

Los archivos de configuración de OpenSSH residen en el directorio/etc/ssh/. El más importante es el /etc/ssh/sshd_config que vamos a modificar aquí.

La documentación de OpenSSH es muy buena, así que siéntase libre de ingresar el comando: apropos openssh or man -k openssh y lea las diferentes páginas man, que son mucho más detalladas que esta página wiki.

Modificando el archivo sshd_config

La primera regla, antes de modificar un archivo de configuración importante es hacer una copia de respaldo. Por ejemplo:

# cp -v /etc/ssh/sshd_config /etc/ssh/sshd_config.ORIG.20120826

El comando mostrado arriba hace una copia del archivo sshd_config y añadir la extención .ORIG (por original, por supuesto)e incluir la fecha de modificación. Aunque no es perfecto, este sistema asegurar que siempre pueda volver a la versión previa del importante archivo ingresando el siguiente código.

# cp -v /etc/ssh/sshd_config.ORIG.20120826 /etc/ssh/sshd_config

Tenga en cuenta que esta es una sugerencia, por supuesto, y se recomienda encarecidamente a los administradores de sistemas que tienen que administrar grandes instalaciones, con cientos de servidores, investigar mejores soluciones, como Puppet u otros gestores de configuración de sistemas distribuidos.

Ahora, edite el archivo /etc/ssh/sshd_config con su editor favorito y ajusta las siguientes lineas:

Cambiar el puerto predeterminado de SSH

Por defecto, OpenSSH escucha en el puerto 22. A veces se recomienda cambiar este puerto predeterminado a algo diferente, como 2222 o 4242. Esto no es una mala idea, pero debe recordar que al escanear su máquina con un programa como nmap obtendrá este nuevo puerto muy rápidamente.Por lo tanto, si bien puede ralentizar algunos ataques en su máquina, no los evitará por completo.

Si desea cambiar el puerto, busque la opción Port en sshd_config, que generalmente está en la parte superior del archivo, y cambie el valor.

Por ejemplo:

Port 22

Puede cambiarse por:

Port 4242

Alternate method of Changing the SSH default port without changing

This suggestion is completely lifted from another site http://null.redcodenetwork.ro/changing-the-ssh-port-without-changing-it/ The idea here is add a call to this script in rc.local so it will run at start up.

To use Download sample at the bottom change as you like and save it in /etc/rc.d/ (make it executable to use) Add this sample below to /etc/rc.d/rc.local

#add ssh_hide to port 8889

if [ -x /etc/rc.d/rc.ssh_hide ]; then
  /etc/rc.d/rc.ssh_hide
fi

What it is doing is making it look like you changed the port ssh is using and provide some additional security. What happens is scanners will continue to see port 22 open and try to go there while your server drops those packets, because the header is not mangled. Real packets come in on port 8889 and are redirected by iptables to port 22 with mangle in the header so they don't get dropped.

rc.ssh_hide
#!/bin/bash
 
######First, set SSHD back to the default port 22. 
######Next, figure out what port or ports you want to do SSH over. 
######Were going to use 99, 88, and 8889 here.
######Now we take care of the Hypothetical Evil Unprivileged User 
######by not accepting anything over those ports in the first place. 
######This is only effective for port 8889 but well do all three ports for the sake of completeness.
 
/usr/sbin/iptables -t filter -A INPUT -p tcp -m multiport --dports 99,88,8889 -j REJECT --reject-with tcp-reset
 
######Then, pick a number between 1 and 4294967295 Ill use 0x13F ()
######Were going to tell iptables to reject anything without this mark coming into port 22.
 
/usr/sbin/iptables -t filter -A INPUT -p tcp -m tcp --dport 22 -m connmark ! --mark 0x13F -j REJECT --reject-with tcp-reset
 
######Now well tell iptables what ports we will accept for ssh.
 
/usr/sbin/iptables -t filter -A FORWARD -p tcp -m multiport --dports 99,88,8889 -j ACCEPT
 
######In the mangle table we slap our mark on these packets.
 
/usr/sbin/iptables -t mangle -A PREROUTING -p tcp -m multiport --dports 99,88,8889 -j CONNMARK --set-mark 0x13F
 
######Finally in the nat table we tell iptables to send the marked packets back to port 22
 
/usr/sbin/iptables -t nat -A PREROUTING -p tcp -m multiport --dport 99,88,8889 -j REDIRECT --to-ports 22
 
exit 0

Note not ipv6 compatible, due to nat (ip6tables not supporting nat)

Forbid root access to your machine

This is probably the single most important change you can do to improve the security of your machine: forbid the root user to access your machine. To do this, look for the following line in sshd_config:

PermitRootLogin yes

And change it to:

PermitRootLogin no

If you apply the changes above, make sure you have at least one user on your machine that can su (switch user) to root or use sudo for more fine-grained system administration permissions. The best way to administrate a server through SSH is to have a user in the wheel group, who can use both sudo and su to become root when need be.

Since most people who try to get into your machine uninvited use brute-force scripts that target the root login, you can already rest a lot easier, knowing this access is locked.

Improve login security and timing

Above and below the PermitRootLogin option, you will find other permissions, that we are going to detail quickly here:

- LoginGraceTime is used to increase, or decrease, the time left to a user to log into the machine. This can be safely be restricted to 5 minutes, with the following:

LoginGraceTime 5m

- MaxAuthTries is used to increse, or decrease, the number of tries allowed to a user to authentify correctly to the machine. This can be restricted to 3 attempts by using:

MaxAuthTries 3

Deny X11 forwarding

Unless you need to use X11 over SSH, you can safely disable it by using the following option:

X11Forwarding no

Please note that disabling X11 does not disable VNC over SSH, for instance. In most cases, it is always a good idea to disable un-needed services.

Restrict SSH login to approved users

If you are sure only specific users need to connect through SSH to your machine, you can declare them using the AllowUsers option. All the users - and only the users - mentioned after the option will be able to connect through SSH to the machine.

AllowUsers jack backup betty

In the example shown above, only user jack, betty and backup will be able to use SSH to connect to the machine. All other users will be denied access. Of course, you should use this option with caution and make sure the (or “a”) default user is included…

Restart the SSH server

The last thing to do, to make sure the SSH server takes the new configuration into account, is to restart the SSH server with the command:

# /etc/rc.d/rc.sshd restart

Your new, and slightly more secure OpenSSH configuration is now in effect. Congratulations!

See Also

Sources

 es:howtos:security:ssh ()