Translation(s): Deutsch - English - Français - Italiano - Español - Português Brasileiro

Afazer: unir essa página com a em francês que é mais completa

Introdução

SSH significa Shell S eguro e é um protocolo para login remoto seguro e outros serviços de rede segura em uma rede insegura 1. Veja Wikipedia - Shell Seguro para informações mais gerais e ssh, lsh-client ou dropbear para as implementações de software SSH, das quais OpenSSH é o mais popular e mais amplamente usado 2. O SSH substitui o telnet não criptografado, rlogin e rsh e adiciona muitos recursos.

Neste documento estaremos usando o conjunto de comandos OpenSSH e também será assumido que as duas variáveis a seguir estão definidas:

remote_host=<the remote computer>
remote_user=<your user name on $remote_host>

Portanto, se você quiser usar os códigos abaixo, primeiro defina essas variáveis para o nome do computador remoto e o nome de usuário nesse computador remoto. Em seguida, cortar e colar os comandos abaixo deve funcionar. remote_host também pode ser um endereço IP.

Instalação

Instalação do cliente

Normalmente o cliente é instalado por padrão. Se não estiver é suficiente rodar como root:

apt-get install openssh-client

Instalação do servidor

O servidor permite conexão remota e é instalado rodando como root:

apt-get install openssh-server

Arquivos de configuração

Os arquivos de configuração principais estão no diretório /etc/ssh :

Além disso, este diretório contém os pares de chaves privadas/públicas que identificam seu servidor:

Desde o OpenSSH 5.73, um novo par de chaves privada/pública está disponível:

Desde o OpenSSH 6.54, um novo par de chaves privada/pública está disponível:

Regerando as chaves do servidor

rm /etc/ssh/ssh_host_*
dpkg-reconfigure openssh-server

Login Remoto

Com senha

Se você deseja logar no $remote_host como o usuário $remote_user simplesmente digite

ssh $remote_user@$remote_host

e então digite a sua senha.

Se o nome de usuário local é igual ao da máquina remote, então você pode remover a parte do $remote_user@ e digitar simplesmente

ssh $remote_host

Se esta é a primeira vez que você efetua login no computador remoto, o ssh perguntará se você tem certeza de que deseja se conectar ao computador remoto. Responda "sim" depois de ter verificado a impressão digital do computador remoto, digite sua senha e o ssh conectará você ao servidor remoto.

Uso de chaves compartilhadas

Uma das funções do ssh é usar um par de chaves privadas/públicas para se conectar a um servidor remoto. Também conhecido como chaves SSH. Esse método permite que você faça login em um servidor remoto sem digitar sua senha todas as vezes. Para fazer isso, você deve gerar um par de chaves privada/pública em sua máquina local e colocar a chave pública no servidor remoto.

Para gerar a chave, use o programa ssh-keygen da seguinte forma

ssh-keygen -t rsa

Este programa gera um par de chaves privada/pública no diretório ~/.ssh. O programa primeiro solicita os arquivos de destino para as chaves, por padrão, localizados em ~/.ssh. Depois é solicitada uma senha.

Nota: Recomendamos não deixar a senha vazia. Um invasor que consiga sua chave privada pode se conectar aos servidores onde você copiou sua chave pública, já que a frase secreta está vazia. Escolha uma senha longa e complexa.

Sua chave privada é id_rsa (não dê para outra pessoa), sua chave pública é id_rsa.pub.

Você copia sua chave pública para um servidor remoto com o comando ssh-copy-id

ssh-copy-id -i ~/.ssh/id_rsa.pub $remote_user@$remote_host

Agora você pode conectar-se simplesmente ao host remoto e a senha para a sua chave privada é solicitada. Uma vez feito isso, você se conecta ao host remoto. No caso de uma nova conexão, a frase secreta não é solicitada novamente durante toda a sessão.

Gerenciamento de chaves

Uso de Interface Gráfica

Opcionalmente, o seahorse é um aplicativo do GNOME que gerencia facilmente chaves e senhas de criptografia através de uma Interface Gráfica de Usuário (GUI) intuitiva. O Seahorse é capaz de fazer várias operações. Como criar chaves SSH ou PGP, configurá-las e armazená-las em cache. Leia mais.

Tornar Seguro

Servidor SSH

Por padrão, um servidor SSH é relativamente seguro. Com a ajuda de algumas boas práticas, opções de configuração e utilitários externos, é possível tornar ainda mais difícil para 'robôs' e crackers

Boas prática com o Servidor SSH

Opções de configuração

(!) Deve-se editar o arquivo /etc/ssh/sshd_config para alterar os parâmetros e depois reiniciar o servidor ssh com

service ssh restart

{i} The options AllowUsers and AllowGroups do not improve the security of a SSH server. But in certain cases their use allows to resist a brute force attack a little longer.

External Utilities

SSH Client

Good practices with SSH Client

Additional Functions

Additional Commands

scp

scp is a command line utilty allowing to transfer files between two machines.

scp $source_file $remote_user@$remote_host:$destination_file

scp $remote_user@$remote_host:$source_file $destination_file

sftp

[empty for now]

text mode

[empty for now]

graphical mode

[empty for now]

clusterssh

[empty for now]

ssh-agent and ssh-add

ssh-agent is a useful utility to manage private keys and their passphrases. It should be invoked at the beginning of your session like so on a bourne shell:

eval `ssh-agent -s`

or on a C shell:

eval `ssh-agent -c`

When a private key is first needed, you are prompted for its passphrase and ssh-agent remembers the key. Whenever that private key is used later on, the passphrase doesn't get asked anymore.

ssh-add can be used to manage the remembered keys:

keychain

Keychain, provided by the package keychain, is a shell script allowing to use the ssh agent in multiple sessions of the same computer. In effect after the first start ssh-agent creates a permanent socket allowing the communication with ssh. This socket is referenced only in the enviromment of the session in which the agent was started. Keychain allows to detect the agent and propagate the access to this agent to other sessions; this allows to use a single instace of ssh-agent per user on a machine.

ssh-askpass

ssh-askpass is an utility to simply the question for the password of a private key when using it. Several implementations exist:

libpam-usb

libpam-usb is an utility (only available up to Debian Jessie) allowing authentication with an USB stick. This package includes a useful utilty : pamusb-agent. This utility, once correctly configured, allows to load the SSH keys present on the USB stick once it is connected and to unload them when it is disconnected.


Remote commands

If you just want to run one command on the remote computer, you don't need to login. You can tell ssh to run the command without login, for instance,

ssh $remote_user@$remote_host 'ls *.txt'

lists all files with extension .txt on the remote computer. This works with single tick quotes '...' as shown here, with double tick quotes "...", and without quotes. There may be differences between these three cases, though, not yet documented here.

SSH into Debian from another OS

Troubleshooting

OpenSSL version mismatch. Built against 1000105f, you have 10001060

If you get an error message like this when starting the ssh daemon, you need to run:

apt-get install openssh-server openssh-client

Also see the bug report.

SSH hangs

Issue

You are trying to SSH into a remote computer. But during SSH log-in the session hangs/freezes indefinitely. Thus you are not presented with the command prompt. And you are not able to use any SSH commands :( When using SSH debug mode the session hangs at this line debug2: channel 0: open confirm rwindow 0 rmax 32768

Possible cause

With some routers behind NAT and when using OpenSSH. During session setup, after the password has been given, OpenSSH sets the TOS (type of service) field in the IP datagram. The router choke on this. The effect is that your SSH session hangs indefinitely. In other words, SSH commands or connections are seldom working or not working at all.

Resolution with IPQoS 0x00

Until your router manufacturer fix their firmware. Here is one option to resolve that issue:

  1. Double check your openssh-server and openssh-client version are 5.7 or more recent. For example the resolution below should work with Debian 7.11 Wheezy or more recent as it comes with OpenSSH version 6.0.

  2. Edit one of the following two files located at:

    ~/.ssh/config

    or

    /etc/ssh/ssh_config

    Note: config file is per user and ssh_config file is for all users and system wide. If unsure edit the appropriate user config file.

    File content before

    Host *

    File content after

    Host *
      IPQoS 0x00
  3. If you have any Terminal/Console window(s) already open. Fully close all of them. Doing so will close any active SSH sessions.
  4. No need to restart OpenSSH or your Debian. Try again to SSH into any remote server. It should work. Done you have successfully fixed that issue :)

    Thanks to Joe and catmaker for this tip :)

    Related documentation at https://www.openssh.com/txt/release-5.7

Resolution with netcat

/!\ WARNING: It is suggested to consider using that other resolution with IPQoS 0x00 instead of using netcat/ProxyCommand nc %h %p option. Because IPQoS 0x00 is the official built-in OpenSSH option. Also IPQoS 0x00 is a more direct way to resolve that issue, and potentially more secure option. Because IPQoS 0x00 uses SSH's built in encryption for secure transfers. Compare to netcat's not encrypted transfers. Sources: 1 2. If you choose to use netcat/ProxyCommand nc %h %p option read on.

Another option to resolve that SSH hangs issue is to use ProxyCommand nc %h %p. To do so follow the same steps as that above resolution with IPQoS 0x00. But replace IPQoS 0x00 with

ProxyCommand nc %h %p

Keep SSH connection alive

For security reason, by default a SSH connection is automatically closed after a set period of time. But in some cases you want to keep that connection open. Such as cloud storage over SSH connection.

/!\ WARNING: Before activating that keep SSH connection alive option. It is suggested to consider securing both your SSH Client and SSH Server. Because for example, there is a risk that if your users leave their SSH session open, and their computer unattended and unlocked. Anyone can approach that computer, then exploit that open SSH connection. For example by using the passwd command, and change the password. And thus gain access to the server. In other words, before activating that keep SSH connection alive option, it is suggested to use your best judgment and good security practices.

For Debian 7.x server

Steps to keep SSH connection alive.

  1. On the SSH server edit "/etc/ssh/sshd_config" file

  2. Add the following at the bottom of that file

    # Keep client SSH connection alive by sending every 300 seconds a small keep-alive packet to the server in order to use ssh connection. 300 seconds equal 5 minutes.
    ClientAliveInterval 300
     
    # Disconnect client after 3333 "ClientAlive" requests. Format is (ClientAliveInterval x ClientAliveCountMax). In this example  (300 seconds x 3333) = ~999,900 seconds = ~16,665 minutes = ~277 hours = ~11 days.
    ClientAliveCountMax 3333
  3. As Root user restart the SSH service

    service sshd restart

    Please note that on recent Debian systems (e.g. Wheezy 7 with current updates as of Nov. 2015), the above command no longer works and returns the error:

    sudo service sshd restart
    sshd: unrecognized service

    However, the following works:

    sudo service ssh restart
    [ ok ] Restarting OpenBSD Secure Shell server: sshd.