SSH

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page SSH and the translation is 56% complete.
Outdated translations are marked like this.
Resources

SSH (Secure SHell) es un programa de terminal cifrado que reemplaza la herramienta clásica telnet en los sistemas operativos tipo Unix.

Además del acceso a la terminal remota proporcionada por el binario principal ssh, la suite de programas SSH ha crecido hasta incluir otras herramientas como scp (Secure Copy Program) y sftp (Secure File Transfer Protocol).

Originalmente, SSH no era libre. Sin embargo, hoy la implementación estándar más popular y de-facto de SSH es OpenSSH de OpenBSD ,que viene pre-instalado en Gentoo.

SSH is multi-platform, and is very widely used: OpenSSH is installed by default on most Unix-like OSs, on Windows10, on MacOS, and can be installed on Android or "jailbroken" iOS (SSH clients are available). This makes SSH a great tool for working with heterogeneous systems.

Instalación

Comprobar la instalación

La mayoría de los despliegues de Gentoo Linux incluyen OpenSSH en el sistema. Esto se puede comprobar lanzando la orden ssh. Si está instalado, se debería mostrar información sobre su utilización:

user $ssh
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-E log_file] [-e escape_char]
           [-F configfile] [-I pkcs11] [-i identity_file]
           [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-p port]
           [-Q cipher | cipher-auth | mac | kex | key]
           [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] [user@]hostname [command]

Si no se muestra información sobre su utilización, probablemente ssh está corrupto o no instalado. También es posible que el usuario reconstruya OpenSSH para incluir una nueva configuración USE. Sea cual sea el caso, continúe para conocer los ajustes USE.

If this does not try to install OpenSSH, the package may have been masked, or even listed in package.provided, though this would be unusual.

Ajustes USE

USE flags for net-misc/openssh Port of OpenBSD's free SSH release

X Add support for X11
X509 Adds support for X.509 certificate authentication
audit Enable support for Linux audit subsystem using sys-process/audit
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
hpn Enable high performance ssh
kerberos Add kerberos support
ldns Use LDNS for DNSSEC/SSHFP validation.
libedit Use the libedit library (replacement for readline)
livecd Enable root password logins for live-cd environment.
pam Add support for PAM (Pluggable Authentication Modules)DANGEROUS to arbitrarily flip
pie Build programs as Position Independent Executables (a security hardening technique)
sctp Support for Stream Control Transmission Protocol
security-key Include builtin U2F/FIDO support
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
ssl Enable additional crypto algorithms via OpenSSL
static !!do not set this during bootstrap!! Causes binaries to be statically linked instead of dynamically
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
verify-sig Verify upstream signatures on distfiles
xmss Enable XMSS post-quantum authentication algorithm

Emerge

Después de cambiar los ajustes USE necesarios, no olvide instalar (o reconstruir) OpenSSH:

root #emerge --ask --changed-use net-misc/openssh

After changing any global USE flags in make.conf that affect the OpenSSH package, emerge world to update to the new USE flags:

root #emerge --ask --verbose --update --deep --newuse @world

Configuración

Crear claves

Con el fin de proporcionar un intérprete de órdenes seguro, se utilizan las claves criptográficas para administrar las funcionalidades de cifrado, descifrado, y de hashing ofrecidas por SSH.

En el primer inicio del servicio SSH, se generarán claves del sistema. Las claves pueden ser (re) generadas mediante la orden ssh-keygen.

Para generar las claves de la versión del protocolo SSH 2 (algoritmos DSA y RSA):

root #/usr/bin/ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N ""
root #/usr/bin/ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N ""

El artículo Secure Secure Shell sugiere el uso de los algoritmos de clave pública Ed25519 y RSA con:

root #/usr/bin/ssh-keygen -t ed25519 -a 100 -f /etc/ssh/ssh_host_dsa_key -N ""
root #/usr/bin/ssh-keygen -t rsa -b 4096 -o -a 100 -f /etc/ssh/ssh_host_rsa_key -N ""

Configuración del servidor

El servidor SSH suele estar configurado en el /etc/ssh/sshd_config aunque también es posible realizar una configuración adicional en archivo /etc/conf.d/sshd de OpenRC, incluyendo el cambio de la ubicación del archivo de configuración. Para obtener información detallada sobre cómo configurar el servidor puede ver el sshd_config man page.

The server provides means to validate its configuration using test mode:

root #/usr/sbin/sshd -t
Importante
Always validate the configuration changes prior restarting the service in order to keep the remote login available.

Configuración del cliente

Los programas cliente ssh cliente y afines (scp, sftp) se puede configurar utilizando los siguientes archivos:

  • ~/.ssh/config
  • /etc/ssh/ssh_config

Para más información lea el manual ssh_config:

user $man ssh_config

Prevención contra intrusos

SSH es un servicio que recibe ataques con bastante regularidad. Herramientas como sshguard y fail2ban monitorizan los registros y prohíben el acceso de usuarios que han intentado conectarse sin éxito en varias ocasiones. Utilícelas de la forma apropiada para asegurar un sistema que reciba ataques con frecuencia.

Utilización

Servicios

Commands to run the SSH server will depend on active init system.

OpenRC

Añada el demonio OpenSSH al nivel de ejecución por defecto:

root #rc-update add sshd default

Arranque el demonio sshd con:

root #rc-service sshd start

El servidor OpenSSH se puede controlar como cualquier otro servicio gestionado por OpenRC:

root #rc-service sshd start
root #rc-service sshd stop
root #rc-service sshd restart
Nota
Las conexiones SSH activas al servidor no se ven afectadas cuando se lanza rc-service sshd restart.

systemd

Para que el demonio OpenSSH arranque cunado lo haga el sistema:

root #systemctl enable sshd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib64/systemd/system/sshd.service.

Para arrancar ahora el demonio OpenSSH:

root #systemctl start sshd.service

Para comprobar si se ha iniciado el servicio:

root #systemctl status sshd.service

Commands

OpenSSH provides several commands, see each command's man page for usage information:

  • scp - secure file copy
  • sftp - secure file transfer
  • ssh-add - add private key identities to the authentication agent
  • ssh-agent - authentication agent
  • ssh-copy-id - use locally available keys to authorize logins on a remote machine
  • ssh-keygen - authentication key utility
  • ssh-keyscan - gather SSH public keys from servers
  • sshd - OpenSSH daemon

Secuencias de escape

Cuando se pulsa la tecla tilde (~) en una sesión de SSH, se inicia un secuencia de escape. Teclee lo siguiente para obtener una lista de opciones:

ssh>~?

Note that escapes are only recognized immediately after a newline. They may not always work with some shells, such as fish.

Connecting to a distant SSH server

Autenticación sin contraseña

Útil para la administración de servidores git.

Cliente

En el cliente, si no se ha realizado ya, cree una pareja de clavers. Esto se puede hacer con la siguiente orden (desde luego sin teclear una frase de acceso):

user $ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/larry/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/larry/.ssh/id_rsa.
Your public key has been saved in /home/larry/.ssh/id_rsa.pub.
The key fingerprint is:
de:ad:be:ef:15:g0:0d:13:37:15:ad:cc:dd:ee:ff:61 larry@client
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|     .           |
| . .. n   .      |
|   . (: . .      |
|  o   . . : .    |
| . ..: >.> .     |
|  * ?. .         |
| o.. .. ..       |
| :. .  ! .       |
+-----------------+

Servidor

Asegúrese de que existe una cuenta para el usuario en el servidor, y luego colocar los clientes id_rsa.pub en el archivo del servidor ~/.ssh/authorized_keys dentro del directorio de inicio del usuario. Esto se puede hacer lanzando la siguiente orden en la computadora cliente (aquí, se necesita introducir la contraseña del servidor):

user $ssh-copy-id <servidor>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/larry/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
larry@<server>'s password: 

Número de clave(s) añadidas: 1

Ahora intente entrar en la máquina usando:   "ssh '<servidor>'" y asegúrese de que solo se han añadido la clave o claves que se desea.

Después se debería poder acceder sin contraseña haciendo lo siguiente

user $ssh <server>
larry@<servidor>

Entonces se debería definir PasswordAuthentication no en el fichero /etc/ssh/sshd_config del servidor.

Prueba de máquina simple

El procedimiento anterior se puede probar a cabo localmente:

user $ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/larry/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
...
user $mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
user $ssh localhost

Terminal multiplexers to preserve sessions

It is possible to use a terminal multiplexer to resume a session after a dropped connection. Tmux and screen are two popular multiplexers that can be used to be able to reconnect to a session, even if a command was running when the connection dropped out.

Mosh may be an alternative for some of SSH's functionality, for spotty connections.

Remote services over ssh

SSH may be used to access remote services through an encrypted "tunnel". Remote service access is detailed in the SSH tunneling and SSH jump host articles.

Resolución de problemas

Hay 3 niveles diferentes modos de depuración que pueden ayudar a solucionar problemas. Con la opcion -v de SSH se imprime mensajes de depuración acerca de su progreso. Esto es útil en la depuración de una conexión , la autenticación y los problemas de configuración. Varias opciones -v aumentan el nivel de detalle. El máximo nivel de detalle es de profundidad tres.

user $ssh example.org -v
user $ssh example.org -vv
user $ssh example.org -vvv

Permissions are too open

An ssh connection will only work if the file permissions of the ~/.ssh directory and contents are correct.

  • The ~/.ssh directory permissions should be 700 (drwx------), i.e. the owner has full access and no one else has any access.
  • Under ~/.ssh:
    • public key files' permissions should be 644 (-rw-r--r--), i.e. anyone may read the file, only the owner can write.
    • all other files' permissions should be 600 (-rw-------), i.e. only the owner may read or write the file.


These permissions need to be correct on the client and server.

Muerte de conexiones de larga vida

Muchos dispositivos de acceso a Internet realizan la Traducción de Direcciones de Red (NAT), un proceso que permite a los dispositivos en una red privada como la que normalmente se encuentran en una casa o lugar de negocio para acceder a redes extranjeras, como lo es Internet, a pesar de tener una única dirección IP en esa red. Por desgracia, no todos los dispositivos NAT son creados iguales, y algunos de ellos se cierran incorrectamente a las conexiones de larga duración, como ocasionalmente usa TCP, como las utilizadas por SSH. Esto es generalmente observable como una incapacidad repentina para interactuar con el servidor remoto incluso si el programa cliente ssh no ha terminado.

Con el fin de resolver el problema, los clientes y los servidores OpenSSH pueden configurarse para enviar un 'keep alive', o mensaje invisible destinado a mantener y confirmar el estado en tiempo real del enlace:

  • Para habilitar el mantenimiento de las conexiones vivas para todos los clientes que se conecten a su servidor local, defina ClientAliveInterval 30 (o algún otro valor en segundos) dentro del archivo /etc/ssh/ssh_config.
  • Para habilitar el mantenimiento de las conexiones vivas para todos los servidores a los que se ha conectado desde su cliente local, defina ServerAliveInterval 30 (o algún otro valor en segundos) dentro del archivo /etc/ssh/ssh_config


For example, to modify the server's configuration:

ARCHIVO /etc/ssh/sshd_configHelp disconnects occur less often (server)
# The following ClientAlive values will keep an inactive session open for 30 minutes
ClientAliveCountMax 60
ClientAliveInterval 30
#
# Deactivate TCPKeepAlive
TCPKeepAlive no

To modify the client's configuration:

ARCHIVO /etc/ssh/ssh_configHelp disconnects occur less often (client)
# The following ServerAlive values will keep an inactive session open for 2 hours
ServerAliveInterval 60
ServerAliveCountMax 120

El reenvío X11 no se realiza ni tunela

Problema: Después de hacer los cambios necesarios a los ficheros de configuración para permitir el reenvío X11, se encuentra con que las aplicaciones se están ejecutando en el servidor y no se reenvían al cliente.

Solución: Lo que seguramente está ocurriendo es que durante la conexión SSH en el servidor remoto la variable DISPLAY no está definida o se redefine después de que lo haga la sesión SSH.

Se pueden hacer pruebas en este escenario tal y como se muestra a continuación conectándose remotamente:

user $echo $DISPLAY
localhost:10.0

La salida debería ser algo similar a localhost:10.0 o localhost2.local:10.0 cuando define X11UseLocalhost no. Si no se muetra el usual :0.0, compruébe para asegurarse de que la variable DISPLAY no está limpiando o reinicializando en ~/.bash_profile. Si es así, elimine o comente su definición para la inicialización de la variable DISPLAY para evitar que se ejecute el código en ~/.bash_profile durante una conexión SSH:

user $ssh -t larry@localhost2 bash --noprofile

Asegúrese de sustituir larry por el nombre de usuario apropiado en la orden de arriba.

Un truco para completar esta tarea que funciona es definir un alias dentro del fichero ~/.bashrc.

ssh-agent

OpenSSH comes with ssh-agent, a daemon to cache and prevent from frequent ssh password entries. When run, the environment variable SSH_AUTH_SOCK is used to point to ssh-agent's communication socket. The normal way to setup ssh-agent is to run it as the top most process of the user's session. Otherwise the environment variables will not be visible inside the session.

Depending on the way the graphical user session is configured to launch, it can be tricky to find a suitable way to launch ssh-agent. As an example for the lightdm display manager, you may edit and change /etc/lightdm/Xsession from

user $exec $command

into

user $exec ssh-agent $command

To tell ssh-agent the password once per session, either run ssh-add manually or make use of the AddKeysToAgent option.

Recent Xfce[1] will start ssh-agent (and gpg-agent) automatically. If both are installed both will be started which makes identity management especially with SmartCards more complicated. Either stop XFCE from autostarting at least SSH's agent or disable both and use your shell, X-session or similar.

user $xfconf-query -c xfce4-session -p /startup/ssh-agent/enabled -n -t bool -s false
user $xfconf-query -c xfce4-session -p /startup/gpg-agent/enabled -n -t bool -s false

Vea también

Copying files to a remote host

The SFTP command, a part of SSH, uses the SSH File Transfer Protocol to copy files to a remote host. rsync is also an alternative for this.

Nota
The OpenSSH 8.0 release notes, from 2019, state "The scp protocol is outdated, inflexible and not readily fixed. We recommend the use of more modern protocols like sftp and rsync for file transfer instead.". The OpenSSH 8.8 release notes, from 2021, state "A near-future release of OpenSSH will switch scp(1) from using the legacy scp/rcp protocol to using SFTP by default.".
  • SCP — an interactive file transfer program, similar to the copy command, that copies files over an encrypted SSH transport.
  • SFTP — an interactive file transfer program, similar to FTP, which performs all operations over an encrypted SSH transport.
  • rsync — a powerful file sync program capable of efficient file transfers and directory synchronization.

Recursos externos