Secure Shell (Español)
Secure Shell (SSH) es un protocolo de red que permite que los datos se intercambien entre dos equipos a través de un canal seguro. El cifrado proporciona confidencialidad e integridad de datos. SSH usa criptografía de clave pública para autenticar el equipo remoto y permitir al mismo autenticar al usuario si es necesario.
SSH nos permite copiar datos de forma segura, gestionar claves RSA para no escribir claves al conectar a los dispositivos y pasar los datos de cualquier otra aplicación por un canal seguro tunelizado mediante SSH
El servidor SSH, por defecto escucha el puerto TCP 22. El cliente SSH se utiliza generalmente para establecer conexiones a un demonio sshd, para tener conexion remota. Ambos se encuentran comúnmente en los sistemas operativos más modernos, incluyendo GNU/Linux.
(Source: Wikipedia:Secure Shell)
Contents
- 1 OpenSSH
- 2 Consejos y trucos
- 2.1 Túnel cifrado
- 2.2 X11 Forwarding
- 2.3 Forwarding Other Ports
- 2.4 Acelerar SSH
- 2.5 Montando un sistema de archivos remoto con SSHFS
- 2.6 Mantener viva
- 2.7 Guardar los datos de conexión en ssh config
- 2.8 Cambiar “bash promp” cuando está conectado a través de ssh
- 2.9 Cerrar sesión de todos los usuarios ssh de forma automática cuando el servidor sshd se apague
- 3 Solución de problemas
- 4 Vea también
- 5 Enlaces y referencias
- 6 Reconocimiento
1 OpenSSH
OpenSSH (OpenBSD Secure Shell) es un conjunto de programas de computadora que proveen una sesión de comunicación encriptada en una red informática que utiliza el protocolo SSH. Fue creado como una alternativa de software libre al software privativo ofrecido por by SSH Communications Security. OpenSSH es desarrollado como parte del proyecto OpenBSD, que está a cargo de Theo de Raadt. OpenSSH es confundido a veces con OpenSSL por la similitud de nombre, sin embargo, los proyectos tienen objetivos distintos y están desarrollados por equipos diferentes.
1.1 Instalando OpenSSH
# pacman -S openssh
1.2 Configurando SSH
1.2.1 Cliente
Para configurar el cliente SSH editamos: /etc/ssh/ssh_config.
Un ejemplo de configuración:
/etc/ssh/ssh_config
# $OpenBSD: ssh_config,v 1.26 2010/01/11 01:39:46 dtucker Exp $ # This is the ssh client system-wide configuration file. See # ssh_config(5) for more information. This file provides defaults for # users, and the values can be changed in per-user configuration files # or on the command line. # Configuration data is parsed as follows: # 1. command line options # 2. user-specific file # 3. system-wide file # Any configuration value is only changed the first time it is set. # Thus, host-specific definitions should be at the beginning of the # configuration file, and defaults at the end. # Site-wide defaults for some commonly used options. For a comprehensive # list of available options, their meanings and defaults, please see the # ssh_config(5) man page. # Host * # ForwardAgent no # ForwardX11 no # RhostsRSAAuthentication no # RSAAuthentication yes # PasswordAuthentication yes # HostbasedAuthentication no # GSSAPIAuthentication no # GSSAPIDelegateCredentials no # BatchMode no # CheckHostIP yes # AddressFamily any # ConnectTimeout 0 # StrictHostKeyChecking ask # IdentityFile ~/.ssh/identity # IdentityFile ~/.ssh/id_rsa # IdentityFile ~/.ssh/id_dsa # Port 22 # Protocol 2,1 # Cipher 3des # Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc # MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160 # EscapeChar ~ # Tunnel no # TunnelDevice any:any # PermitLocalCommand no # VisualHostKey no # ProxyCommand ssh -q -W %h:%p gateway.example.com
Se recomienda cambiar la linea de Protocol de la siguiente manera:
Protocol 2
Con esto decimos, que solo se utilizará Protocol 2 , ya que Protocol 1 es considerado inseguro.
1.2.2 Demonio (daemon)
Para configurar el demonio SSH editamos: /etc/ssh/sshd_config.
Un ejemplo de configuración:
/etc/ssh/sshd_config
# $OpenBSD: sshd_config,v 1.82 2010/09/06 17:10:19 naddy Exp $ # This is the sshd server system-wide configuration file. See # sshd_config(5) for more information. # This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin # The strategy used for options in the default sshd_config shipped with # OpenSSH is to specify options with their default value where # possible, but leave them commented. Uncommented options change a # default value. #Port 22 #AddressFamily any #ListenAddress 0.0.0.0 #ListenAddress :: # The default requires explicit activation of protocol 1 #Protocol 2 # HostKey for protocol version 1 #HostKey /etc/ssh/ssh_host_key # 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 # Lifetime and size of ephemeral version 1 server key #KeyRegenerationInterval 1h #ServerKeyBits 1024 # Logging # obsoletes QuietMode and FascistLogging #SyslogFacility AUTH #LogLevel INFO # Authentication: #LoginGraceTime 2m #PermitRootLogin yes #StrictModes yes #MaxAuthTries 6 #MaxSessions 10 #RSAAuthentication yes #PubkeyAuthentication yes #AuthorizedKeysFile .ssh/authorized_keys # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts #RhostsRSAAuthentication no # similar for protocol version 2 #HostbasedAuthentication no # Change to yes if you do not trust ~/.ssh/known_hosts for # RhostsRSAAuthentication and HostbasedAuthentication #IgnoreUserKnownHosts no # Don't read the user's ~/.rhosts and ~/.shosts files #IgnoreRhosts yes # To disable tunneled clear text passwords, change to no here! #PasswordAuthentication yes #PermitEmptyPasswords no # Change to no to disable s/key passwords ChallengeResponseAuthentication no # Kerberos options #KerberosAuthentication no #KerberosOrLocalPasswd yes #KerberosTicketCleanup yes #KerberosGetAFSToken no # GSSAPI options #GSSAPIAuthentication no #GSSAPICleanupCredentials yes # Set this to 'yes' to enable PAM authentication, account processing, # and session processing. If this is enabled, PAM authentication will # be allowed through the ChallengeResponseAuthentication and # PasswordAuthentication. Depending on your PAM configuration, # PAM authentication via ChallengeResponseAuthentication may bypass # the setting of "PermitRootLogin without-password". # If you just want the PAM account and session checks to run without # PAM authentication, then enable this but set PasswordAuthentication # and ChallengeResponseAuthentication to 'no'. UsePAM yes #AllowAgentForwarding yes #AllowTcpForwarding yes #GatewayPorts no #X11Forwarding no #X11DisplayOffset 10 #X11UseLocalhost yes #PrintMotd yes #PrintLastLog yes #TCPKeepAlive yes #UseLogin no #UsePrivilegeSeparation yes #PermitUserEnvironment no #Compression delayed #ClientAliveInterval 0 #ClientAliveCountMax 3 #UseDNS yes #PidFile /var/run/sshd.pid #MaxStartups 10 #PermitTunnel no #ChrootDirectory none # no default banner path #Banner none # override default of no subsystems Subsystem sftp /usr/lib/ssh/sftp-server # Example of overriding settings on a per-user basis #Match User anoncvs # X11Forwarding no # AllowTcpForwarding no # ForceCommand cvs server
Para permitir el acceso sólo a algunos usuarios añada esta línea:
AllowUsers user1 user2
Para deshabilitar el acceso como root a través de SSH, añada lo siguiente:
PermitRootLogin no
También puede descomentar la opción de banner y editar el archivo /etc/issue para un agradable mensaje de bienvenida.
El puerto por defecto que usa SSH puede ser detectado mediante el uso de un escáner, como nmap, el cambio de puerto reducirá el número de entradas de registro causados por los intentos automatizados de autenticación. Para ayudar a seleccionar un puerto revise la lista de números de puertos TCP y UDP..
1.3 Gestionar demonio SSHD
Añada sshd a la linea de "DAEMONS" en el archivo /etc/rc.conf:
DAEMONS=(... ... sshd ... ...)
Para iniciar / reiniciar / detener el demonio, utilice lo siguiente:
# rc.d {start|stop|restart} sshd
1.4 Conectar a un servidor SSH
Para conectar a un servidor, ejecute:
$ ssh -p puerto usuario@dirección-del-servidor
2 Consejos y trucos
2.1 Túnel cifrado
Esto es muy útil para los usuarios de ordenadores portátiles conectados a varias conexiones inalámbricas inseguras. Lo único que necesitas es un servidor SSH corriendo en un lugar un tanto seguro, como en su casa o en el trabajo. Puede ser útil usar un servicio de DNS dinámico como noIP para no tener que recordar la dirección IP del servidos al que desea conectarse.
2.1.1 Paso 1: Iniciar la conexión
Ejecute el siguiente comando en su terminal para iniciar la conexión:
$ ssh -ND 4711 usuario@host
donde "usuario" es su nombre de usuario en el servidor SSH ejecutandose en el "host". Preguntará por su contraseña, y luego estará conectado! La opción "N" desactiva el prompt interactivo y la opción "D" especifica el puerto local en el cual escuchar (puede elegir el numero de puerto que usted quiera).
Una forma de hacer esto facilmente es agregar un alias a su archivo ~/.bashrc como lo siguiente:
alias sshtunnel="ssh -ND 4711 -v usuario@host"
Es de gran ayuda usar la opción "-v" (modo verbose), porque usted puede comprobar que en realidad está conectado a esa salida. Ahora sólo tienes que ejecutar el comando "sshtunnel".
El paso anterior es completamente inútil si no se configura el navegador web (u otros programas) para utilizar el túnel recién creado, la version actual de SSH soporta SOCKS4 y SOCKS5, usted puede usar cualquiera de ellos.
- Para IceCat o Iceweasel-libre: Editar → Preferencias → Avanzadas → Red → Conexión → Configuracion:
- Marque la casilla "Configuración manual de proxy" y escriba "localhost" en el campo "Servidor SOCKS" luego escriba su número de puerto en el siguiente campo de texto (Yo usé el puerto 4711, vease arriba).
Tanto IceCat como Iceweasel-libre no hacen automáticamente las solicitudes DNS a través del túnel. Esta preocupación potencial de privacidad puede ser mitigada por los siguientes pasos:
- Escriba about:config en la barra de direcciones de Icecat o Iceweasel-libre.
- Busque “network.proxy.socks_remote_dns”
- Cambie el valor false a true.
- Reinicie su navegador web.
Listo. Disfrute de un tunel seguro!
2.2 X11 Forwarding
Para ejecutar programas gráficos a través de una conexión SSH usted puede habilitarX11 forwarding. Esta opción deber ser especificada en el archivo de configuración del servidor y del cliente (entiéndase "cliente" como su equipo en el cual su servidor X11 es ejecutado, y correra aplicaciones X en el "servidor").
Instale xorg-xauth en el servidor:
# pacman -S xorg-xauth
- Habilite la opción AllowTcpForwarding en el archivo sshd_config del servidor.
- Habilite la opción X11Forwarding en el archivo sshd_config del servidor.
- Habilite la opción X11DisplayOffset en el archivo sshd_config del servidor y verifique que tenga el valor 10.
- Habilite la opción X11UseLocalhost en el archivo sshd_config del servidor.
Tambien:
- Habilite la opción ForwardX11 en el archivo ssh_config del cliente.
Habilitar ForwardX11Trusted ayudará cuando gui dibuje mal.
Para usar el forwarding, acceda al servidor a través de ssh de la siguiente manera:
$ ssh -X -p puerto usuario@dirección-del-servidor
Si recibes errores intentando ejecutar aplicaciones gráficas prueba con trusted forwarding (ForwardX11Trusted ) de la siguiente manera:
$ ssh -Y -p puerto usuario@dirección del servidor
Ya puede empezar cualquier programa de X en el servidor remoto, la salida será enviada a la sesión local:
$ xclock
Si consigues errores del tipo "Cannot open display" (no se puede abrir la pantalla) intente el siguiente comando como usuario:
$ xhost +
el comando anterior permitirá a cualquiera que transmita aplicaciones X11. Para solo permitir algún tipo en particular de host:
$ xhost +hostname
donde hostname es el nombre del host al cual desea transmitir. Para más detalles consulte el "man xhost".
Tenga cuidado con algunas aplicaciones, ya que comprueban si hay una instancia en ejecución en la máquina local. IceCat e Iceweasel-libre son un ejemplo. Utilise el siguiente parámetro para no iniciar una instancia remota en el equipo local.
$ icecat -no-remote
o en su caso
$ iceweasel -no-remote
2.3 Forwarding Other Ports
In addition to SSH's built-in support for X11, it can also be used to securely tunnel any TCP connection, by use of local forwarding or remote forwarding.
Local forwarding opens a port on the local machine, connections to which will be forwarded to the remote host and from there on to a given destination. Very often, the forwarding destination will be the same as the remote host, thus providing a secure shell and, e.g. a secure VNC connection, to the same machine. Local forwarding is accomplished by means of the -L switch and it's accompanying forwarding specification in the form of <tunnel port>:<destination address>:<destination port>.
Thus:
$ ssh -L 1000:mail.yourmailserver.com:25 192.168.0.100
will use SSH to login to and open a shell on 192.168.0.100, and will also create a tunnel from the local machine's TCP port 1000 to mail.yourmailserver.com on port 25. Once established, connections to localhost:1000 will connect to the your mail server SMTP port. To your mail server, it will appear that any such connection (though not necessarily the data conveyed over the connection) originated from 192.168.0.100, and such data will be secure as between the local machine and 192.168.0.100, but not between 192.168.0.100, unless other measures are taken.
Similarly:
$ ssh -L 2000:192.168.0.100:6001 192.168.0.100
will allow connections to localhost:2000 which will be transparently sent to the remote host on port 6001. The preceding example is useful for VNC connections using the vncserver utility--part of the tightvnc package--which, though very useful, is explicit about its lack of security.
Remote forwarding allows the remote host to connect to an arbitrary host via the SSH tunnel and the local machine, providing a functional reversal of local forwarding, and is useful for situations where, e.g., the remote host has limited connectivity due to firewalling. It is enabled with the -R switch and a forwarding specification in the form of <tunnel port>:<destination address>:<destination port>.
Thus:
$ ssh -R 3000:irc.freenode.net:6667 192.168.0.200
will bring up a shell on 192.168.0.200, and connections from 192.168.0.200 to itself on port 3000 (remotely speaking, localhost:3000) will be sent over the tunnel to the local machine and then on to irc.freenode.net on port 6667, thus, in this example, allowing the use of IRC programs on the remote host to be used, even if port 6667 would normally be blocked to it.
Both local and remote forwarding can be used to provide a secure "gateway," allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. <tunnel address>:<tunnel port>:<destination address>:<destination port>. The <tunnel address> can be any address on the machine at the start of the tunnel, localhost, * (or blank), which, respectively, allow connections via the given address, via the loopback interface, or via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the <tunnel address> is set to localhost. Local forwarding requires no additional configuration, however remote forwarding is limited by the remote server's SSH daemon configuration. See the GatewayPorts option in sshd_config(5) for more information.
2.4 Acelerar SSH
Usted puede hacer todas las sesiones en el mismo host utilizando una única conexión, la cual será de gran velocidad de hasta inicios de sesión subsiguientes, esto mediante la adición de estas líneas en el host adecuado en /etc/ssh/ssh_config:
ControlMaster auto ControlPath ~/.ssh/socket-%r@%h:%p
Al cambiar los valores utilizados por SSH a una menor demanda de recursos puede aumentar la velocidad de la CPU. En este aspecto, las mejores opciones son arcfour y blowfish-cbc Por favor, no haga esto a menos que sepa lo que está haciendo; arcfour tiene una serie de debilidades conocidas. Para usarlas, ejecute ssh con la opción "c", de la siguiente manera:
$ ssh -c arcfour,blowfish-cbc usuario@dirección-del-servidor
Para usarlos de forma permanente, añada esta línea al host apropiado en /etc/ssh/ssh_config:
Ciphers arcfour,blowfish-cbc
Otra opción para mejorar la velocidad es habilitar la compresión con el sufijo "C". Una solución permanente es agregar esta linea debajo del host correcto en /etc/ssh/ssh_config:
Compression yes
El tiempo de inicio de sesión puede ser acortado usando el sufijo "4", que saltea la búsqueda IPv6. Esto puede hacerse permanente añadiendo esta línea bajo el host correcto en /etc/ssh/ssh_config:
AddressFamily inet
Another way of making these changes permanent is to create an alias in ~/.bashrc:
alias ssh='ssh -C4c arcfour,blowfish-cbc'
2.4.1 Solución de problemas
Asegurate de que la cadena DISPLAY apunte al servidor remoto:
$ ssh -X usuario@dirección-del-servidor server $ echo $DISPLAY localhost:10.0 server $ telnet localhost 6010 localhost/6010: lookup failure: Temporary failure in name resolution
puede ser solucionado agregando localhost a /etc/hosts.
2.5 Montando un sistema de archivos remoto con SSHFS
Instale sshfs
# pacman -S sshfs
Carge el modulo “fuse”
# modprobe fuse
Agrege “fuse” a la linea de MODULES en /etc/rc.conf para que sea ejecutado en cada inicio del sistema.
MODULES=(... ... fuse ... ...)
Montar la carpeta remota usando sshfs
# mkdir ~/remote_folder # sshfs usuario@servidor_remoto:/tmp ~/remote_folder
El comando anterior hará que la carpeta /tmp en el servidor remoto sea montada como ~/remote_folder en la maquina local. La copia de cualquier archivo en esta carpeta dará lugar a una copia transparente sobre la red red utilizando SFTP. La misma se refiere también a la edición directa de archivos, la creación o eliminación.
Una vez finalizado el trabajo con el sistema de archivos remoto, podemos desmontar la carpeta remota mediante el siguiente comando
# fusermount -u ~/remote_folder
Si trabajamos con esta carpeta a diario, es recomendable agregarlo a la tabla /etc/fstab. De esta forma se puede montar de forma automática en el arranque o manualmente (si se elige la opción noauto), sin la necesidad de especificar la ubicación remota en todo momento. Aquí hay una entrada de ejemplo en la tabla
sshfs#USER@remote_server:/tmp /full/path/to/directory fuse defaults,auto,allow_other 0 0
2.6 Mantener viva
Tu sesion ssh sera automáticamente desconectada si ésta se encuentra inactiva. Para mantener activa la conexión agrega esto a ~/.ssh/config o a /etc/ssh/ssh_config en el cliente.
ServerAliveInterval 120
Esto enviará una señal de "keep alive" (mantener viva) al servidor cada 120 segundos
Por el contrario, para mantener vivas las conexiones entrantes, se puede establecer del siguiente modo:
ClientAliveInterval 120
(o algún otro numero mayor que 0) en /etc/ssh/sshd_config del servidor.
2.7 Guardar los datos de conexión en ssh config
Cada vez que desee conectarse a un servidor ssh, por lo general tiene que escribir al menos su dirección y nombre de usuario. Para evitar el trabajo de estar ingresando sus datos cada que usted se conecte al servido y mas aún si usted lo hace con regularidad, puede usar el archivo personal $HOME/.ssh/config o el global /etc/ssh/ssh_config tal como se muestra en el siguiente ejemplo:
$HOME/.ssh/config
Host myserver HostName 123.123.123.123 Port 12345 User bob Host other_server HostName test.something.org User alice CheckHostIP no Cipher blowfish
Ahora sólo tiene que conectarse al servidor utilizando el nombre especificado:
$ ssh myserver
Para ver una lista completa de las opciones posibles, echa un vistazo a la página de manual ssh_config en el sistema o la documentación de ssh_config en el sitio web oficial.
2.8 Cambiar “bash promp” cuando está conectado a través de ssh
A veces puede ser útil poder hacer la diferencia entre el “bash promp” local y el remoto, en particular cuando ambos estén configurados de la misma manera. Para ello, basta con introducir esto en su bashrc:
$HOME/.bashrc
if [ -n "$SSH_CLIENT" ]; then PS1='\[\e[0;33m\]\u@\h:\wSSH$\[\e[m\] ' else PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\ e[m\] ' fi
Ver Color Bash Prompt para obtener más información acerca de la personalización de la variable “PS1”.
2.9 Cerrar sesión de todos los usuarios ssh de forma automática cuando el servidor sshd se apague
Para cerrar sesión de todos los usuarios ssh de forma automática cuando el servidor sshd se apague, reinicie o detenga, añada la siguiente línea a /etc/rc.local.shutdown en el servidor sshd:
who | cut -d " " -f1 | uniq | xargs pkill -KILL -u
Esto evita que las terminales de los clientes ssh se cuelguen durante un prolongado tiempo, y finalmente terminen con: (Error al escribir: Tubería rota)
Write failed: Broken pipe
3 Solución de problemas
3.1 Conexión rechazada o un problema de tiempo de espera
3.1.1 ¿SSH se está ejecutando y escuchando?
# netstat -tnlp | grep ssh
Si el comando anterior no muestra nada, entonces SSH no está funcionando. Revise los errores en /var/log/(messages, etc).
3.1.2 ¿Existen reglas de firewall bloqueando la conexión?
Verifique las reglas de iptables para asegurarse de que no interfieran
o:
# rc.d stop iptables
o:
# iptables -P INPUT ACCEPT # iptables -P OUTPUT ACCEPT # iptables -F INPUT # iptables -F OUTPUT
3.1.3 Aún no llega tráfico a su equipo
Inicie un volcado de tráfico en la computadora en la que está teniendo problemas con:
# tcpdump -lnn -i any port ssh and tcp-syn
Ahora pruebe de nuevo la conexión. Si usted no ve ninguna salida al intentar conectarse, algo que está fuera de su ordenador está bloqueando el tráfico (por ejemplo; hardware firewall, NAT router etc.).
3.1.4 Connection reset by peer
Versiones recientes de openssh a veces fallan con el mensaje de error anterior. En ese caso, edite el archivo
~/.ssh/config
o crear, si no existe, y gregue la siguiente línea:
HostKeyAlgorithms ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss
Con OpenSSH 5.9, la solución anterior no funciona. En su lugar, escriba en ~/.ssh/config las siguientes lineas:
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc MACs hmac-md5,hmac-sha1,hmac-ripemd160
Véase también la discusión en el foro de errores OpenSSH.
3.2 "[your shell]: No such file or directory" / ssh_exchange_identification
Una causa posible de esto es la necesidad de ciertos clientes SSH para encontrar una ruta absoluta en $SHELL, incluso si el binario de shell está situado en una de las entradas del $PATH. Otra razón puede ser que el usuario no está añadido al grupo “network”.
4 Vea también
5 Enlaces y referencias
- A Cure for the Common SSH Login Attack
- Defending against brute force ssh attacks
- OpenSSH key management, Part 1 and Part 2 on IBM developerWorks