OpenSSH
SSH
(Secure Shell) é um protocolo que facilita comunicações seguras entre dois sistemas usando uma arquitetura cliente-servidor e permite usuários conectarem a sistemas de servidor hóspede remotamente. Ao contrário de outros protocolos de comunicação remota, como FTP
, Telnet
, ou rlogin, SSH criptografa a sessão de login, tornando a conexão difícil para invasores coletarem senhas não criptografadas.
A ssh é um programa designado para substituir aplicações terminais de acesso remoto antigas e menos seguro, como telnet ou rsh. Um programa relacionado chamado scp substitui programas mais antigos designado para compartilhar arquivos entre usuários, como rcp. Porque há aplicações antigas que não encripta as senhas que são compartilhadas entre o cliente e a máquina remota, evitando-os sempre que possível. Usando métodos de seguros de acesso à sistemas remotos, diminuindo os riscos para ambos o cliente e ao remoto.
Fedora includes the general OpenSSH package, openssh, as well as the OpenSSH server, openssh-server, and client, openssh-clients, packages. Note, the OpenSSH packages require the OpenSSL package openssl-libs, which installs several important cryptographic libraries, enabling OpenSSH to provide encrypted communications.
O Protocolo SSH
Por que usar o SSH?
Invasor em potêncial tem uma variedade de ferramentas disponíveis com eles para interromper, interceptar e roteador o tráfego de dados em um esforço para ganhar acesso ao sistema. Em termos gerais, essas ameaças podem ser categorizados como seguinte:
- Interceptando a comunicação entre dois sistemas
-
O atacante pode estar em algum lugar na internet entre a comunicação, copiando as informações que estão sendo passadas entre eles. Ele pode interceptar e manter a informação ou alterar a informação e enviar ao destinatário.
Esse ataque são normalmente realizados usando um packet sniffer, é muito comum utilitários de rede que captura cada pacote que trafega pela rede e analisa o conteúdo.
- Copiando um usuário particular
-
O sistema do atacante é configurado para danificar o futuro alvo da transmissão. Se essa estratégia funciona, o sistema do usuário permanecerá fora de uso que está comunicando com um usuário errado.
Esse ataque pode ser realizado usando uma técnica conhecida como DNS poisoning, ou via um IP spoofing. No primeiro caso, o invasor faz uso de um servidor DNS malicioso para encaminhar para usuário duplicado mal-intencionado. No segundo caso, o invasor envia um pacote falsificado que aparenta ser de uma fonte confiável.
Ambas técnicas de interceptar possíveis informações sensíveis e se caso for interceptada por um razão hostil, os resultados pode ser desastroso. Se o SSH for utilizado por um acesso via shell remoto essas ameaças de segurança pode ser grandemente diminuída. Isso porque o cliente e servidor SSH faz uso de uma assinatura digital para verificar sua identidade. Adicionalmente, todas as comunicações entre o cliente e o sistema servidor está encriptado. Tentativas de fraudar a identidade de ambos os lados da comunicação não funciona, desde de que cada pacote é encriptado usando uma chave conhecida somente pelos usuários local e o sistema remoto.
Recursos Principais
O protocolo SSH provê os seguintes proteções:
- Ninguém pode fingir como sendo o servidor pretendido
-
Depois de uma conexão inicial, o cliente pode verificar que esta conectando o mesmo servidor que estava conectado anteriormente.
- Ninguém pode capturar informação de autenticação
-
O cliente transmite sua informação de autenticação para o servidor usando uma encriptação forte de 128-bit.
- Ninguém pode interromper a comunicação
-
Todos os dados enviados e recebidos durante a sessão foi transferida usando uma encriptação de 128-bit, fazendo com que a interceptação de transmissão seja extremamente difícil de ser desencriptada e lida.
Adicionalmente, isso também oferece as seguintes opções:
- Fornece um método seguro para usar aplicação gráfica na Internet
-
Usando uma técnica chamada X11 forwarding, o cliente pode transmitir X11 (X Window System) aplicações do servidor. Note que se você selecionar
ForwardX11Trusted com a opção `yes`ou se você usar SSH com a opção [option]
-Y`, seu bypass de X11 SECURITY controles de extensão, no que pode resultar em uma ameaça. - Fornece uma meio mais seguro do que os protocolos inseguros
-
O protocolo SSH encripta tudo que é enviado e recebido. Usando uma técnica chamada port forwarding, um servidor SSH pode se tornar um meio para os protocolos que não são seguros, como POP, e aumentar a segurança geral do sistema e dados.
- Pode ser utilizado para criar uma canal seguro
-
O servidor e cliente OpenSSH pode ser configurado para criar um túnel similar a um túnel virtual privado para o tráfego entre a máquina servidor e a cliente.
- Suporta autenticação Kerberos
-
Servidores e cliente OpenSSH pode ser configurado para autenticar usando a GSSAPI (Generic Security Services Application Program Interface) implementação do protocolo de autenticação de rede do Kerberos.
Versões de Protocolo
Duas variações do SSH atualmente existem: versão 1 e a versão 2. A suíte do OpenSSH Fedora utiliza a versão 2 do SSH, no que tem um melhor algoritmo de troca de chave, não vulnerável em comparação a vulnerável versão 1. No entanto, por questões de compatibilidade, o OpenSSH suíte da suporte a versão 1 também, contudo a versão 1 é desabilitada por padrão e precisa ser ativada nas configurações da aplicação.
Evitar usar a versão 1 do SSH
Para garantir uma máxima segurança para a sua conexão, é recomendado que somente a versão 2 do SSH server e cliente seja utilizado sempre que possível. |
Sequência de Eventos de uma Conexão SSH
As seguintes series de eventos ajuda em proteger a integridade da comunicação SSH entre os usuários.
-
Um handshake criptografado é realizado para que o cliente consiga verificar que esta comunicando com o servidor correto.
-
A camada de transporte da comunicação entre o cliente e a máquina remota são encriptada usando um código simétrica.
-
O cliente se autentica ao servidor.
-
O cliente interage com o usuário remoto sobre uma conexão criptografada.
Transport Layer A regra principal da camada de transporte é uma facilitação sem risco e uma comunicação segura entre os dois usuários no momento da autenticação e durante comunicação subsequente. A camada de transporte finaliza isso por lidando com encriptação e desencriptação de dados, e provendo uma proteção de integridade de pacote de dados conforme deles são enviados e recebidos. A camada de transporte também fornece o empacotamento e o envio das informações.
Assim que um cliente SSH se comunica com o servidor a chave de informação é trocada para que os dois sistemas possam corretamente construir una camada de transporte. Os passos seguintes que ocorre durante essa troca:
-
Chaves podem ser trocadas
-
Uma encriptação de chave pública é determinada
-
Um algoritmo de encriptação simétrica é determinada
-
Um algoritmo de autenticação de mensagem é determinada
-
Um algoritmo de chave é determinado
Durante o troca de chave, o servidor se identifica com o cliente com uma única host key. Se o cliente nunca se comunicou com esse servidor em particular antes, a chave do cliente servidor é desconhecida para o cliente e não conecta. OpenSSH notifica o usuário que a autenticidade do usuário não pode ser estabelecida e exibe uma mensagem se ele aceita ou rejeita. É esperado que o usuário independentemente verifique a nova chave de acesso do usuário antes de aceitar. Nas seguintes conexões, a chave do servidor é verificada opondo-se a versão salva no cliente, provendo confidencialidade que o cliente de fato esta se comunicando com o servidor pretendido. Se, em um futuro a chave de usuário não coincidir, o usuário pode remover a versão salva do cliente antes que a conexão ocorra.
Sempre verificar a integridade de um novo servidor SSH
Há possibilidade de um atacante fingindo ser um servidor SSH durante o contato inicial com o sistema local que não sabe a diferença entre um servidor confiável e um falso de um atacante. Para ajudar a prevenir isso, verifique a integridade do novo servidor SSH realizando o contato com o administrador do servidor antes de conectar pela primeira vez ou em evento que a chave de acesso não é validada. |
O SSH é desenvolvido para funcionar com quase todos os algoritmos de chave pública e formato de codificação. Depois uma troca inicial de chave, cria um código usado para trocar e trocar de forma secreta, os dois sistemas imediatamente começa calculando novas chaves e algoritmos para autenticação segura e futuro envio de dados.
Depois de uma certa quantia de dados que foram transmitidas usando uma chave e algoritmo (the quantia exata dependo da implementação do SSH), uma nova troca de chave ocorre, estabelecendo outro conjunto de chave de criptografia valida e um novo secreto. Mesmo se um atacante descobrir a chave de criptografia, essa informação só é útil por um curto período de tempo.
Authentication Assim que a camada de transporte estabelece um túnel seguro para trafegar informações entre os dois sistemas, o servidor fala para o cliente os diferentes métodos de autenticação suportados, assim como usar uma chave criptografada privada ou digitar uma senha. O cliente então tenta se autenticar ao servidor usando um dos métodos suportados.
Os servidores e clientes SSH podem configurar para permitir diferentes tipos de autenticação, no que fornece para cada uma ótima quantidade de controle. O servidor pode decidir qual método de encriptação é suportada baseada no modelo de segurança, e o cliente pode escolher qual método de autenticação tentar das opções disponíveis.
Channels After a successful authentication over the SSH transport layer, multiple channels are opened via a technique called multiplexing[1]. Each of these channels handles communication for different terminal sessions and for forwarded X11 sessions.
Both clients and servers can create a new channel. Each channel is then assigned a different number on each end of the connection. When the client attempts to open a new channel, the clients sends the channel number along with the request. This information is stored by the server and is used to direct communication to that channel. This is done so that different types of sessions do not affect one another and so that when a given session ends, its channel can be closed without disrupting the primary SSH connection.
Channels also support flow-control, which allows them to send and receive data in an orderly fashion. In this way, data is not sent over the channel until the client receives a message that the channel is open.
The client and server negotiate the characteristics of each channel automatically, depending on the type of service the client requests and the way the user is connected to the network. This allows great flexibility in handling different types of remote connections without having to change the basic infrastructure of the protocol.
Configuring OpenSSH
In order to perform tasks described in this section, you must have superuser privileges. To obtain them, log in as root
by typing:
su -
Arquivos de Configuração
There are two different sets of configuration files: those for client programs (that is, ssh, scp, and sftp), and those for the server (the sshd daemon). System-wide SSH configuration information is stored in the /etc/ssh/
directory as described in System-wide configuration files. User-specific SSH configuration information is stored in ~/.ssh/
within the user’s home directory as described in User-specific configuration files.
File | Description |
---|---|
|
Contains Diffie-Hellman groups used for the Diffie-Hellman key exchange which is critical for constructing a secure transport layer. When keys are exchanged at the beginning of an SSH session, a shared, secret value is created which cannot be determined by either party alone. This value is then used to provide host authentication. |
|
The default SSH client configuration file. Note that it is overridden by |
|
The configuration file for the sshd daemon. |
|
The ECDSA private key used by the sshd daemon. |
|
The ECDSA public key used by the sshd daemon. |
|
The RSA private key used by the sshd daemon for version 1 of the SSH protocol. |
|
The RSA public key used by the sshd daemon for version 1 of the SSH protocol. |
|
The RSA private key used by the sshd daemon for version 2 of the SSH protocol. |
|
The RSA public key used by the sshd daemon for version 2 of the SSH protocol. |
|
The PAM configuration file for the sshd daemon. |
|
Configuration file for the |
File | Description |
---|---|
|
Holds a list of authorized public keys for servers. When the client connects to a server, the server authenticates the client by checking its signed public key stored within this file. |
|
Contains the ECDSA private key of the user. |
|
The ECDSA public key of the user. |
|
The RSA private key used by ssh for version 2 of the SSH protocol. |
|
The RSA public key used by ssh for version 2 of the SSH protocol. |
|
The RSA private key used by ssh for version 1 of the SSH protocol. |
|
The RSA public key used by ssh for version 1 of the SSH protocol. |
|
Contains host keys of SSH servers accessed by the user. This file is very important for ensuring that the SSH client is connecting to the correct SSH server. |
For information concerning various directives that can be used in the SSH configuration files, see the ssh_config
(5) and sshd_config
(5) manual pages.
Iniciando um Servidor OpenSSH
Tenha certeza que possui pacotes relevantes instalados
To run an OpenSSH server, you must have the openssh-server package installed. See Installing Packages for more information on how to install new packages in Fedora 26. |
To start the sshd daemon in the current session, type the following at a shell prompt as root
:
~]# systemctl start sshd.service
To stop the running sshd daemon in the current session, use the following command as root
:
~]# systemctl stop sshd.service
Se você quer uma daemon para começar automaticamente o tempo de inicialização, digite 'root':
~]# systemctl enable sshd.service ln -s '/usr/lib/systemd/system/sshd.service' '/etc/systemd/system/multi-user.target.wants/sshd.service'
Veja Services and Daemons para mais informações de como configurar serviços no Fedora.
Note que se você reinstalar o sistema, um novo conjunto de chaves de identificação é criada. Como resultado, clientes que conectou ao sistema com qualquer ferramenta OpenSSH antes de reinstalar irá ver a seguinte mensagem:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed.
To prevent this, you can backup the relevant files from the /etc/ssh/
directory (see System-wide configuration files for a complete list), and restore them whenever you reinstall the system.
Requerendo SSH para Conexões Remotas
For SSH to be truly effective, using insecure connection protocols should be prohibited. Otherwise, a user’s password may be protected using SSH for one session, only to be captured later while logging in using Telnet. Some services to disable include telnet, rsh, rlogin, and vsftpd.
Esses serviços não podem ser instalados por padrão em Fedora. Se for requerido, tenha certeza que esses serviços não esta em execução, digite o seguinte comando no terminal:
systemctl stop telnet.service systemctl stop rsh.service systemctl stop rlogin.service systemctl stop vsftpd.service
Para desabilitar esses serviços na inicialização, digite:
systemctl disable telnet.service systemctl disable rsh.service systemctl disable rlogin.service systemctl disable vsftpd.service
Veja Services and Daemons para mais informações de como configurar serviços no Fedora.
Usando Autenticação Baseada em Chave
To improve the system security even further, generate SSH key pairs and then enforce key-based authentication by disabling password authentication. To do so, open the /etc/ssh/sshd_config
configuration file in a text editor such as vi or nano, and change the PasswordAuthentication
option as follows:
PasswordAuthentication no
If you are working on a system other than a new default installation, check that PubkeyAuthentication no has not been set. If connected remotely, not using console or out-of-band access, testing the key-based log in process before disabling password authentication is advised.
Para ser possível usar ssh, scp, ou sftp para conectar ao servidor de máquina cliente, tem que gerar uma chave de autenticação seguindo os passos abaixo. Note que as chaves precisam ser geradas para cada usuário separadamente.
Fedora 26 utilize o Protocolo SSH 2 e chave RSA por padrão (veja Protocol Versions para mais informações).
Não gere um par de chave como administrador
Se você completar os passos como 'administrador', somente o 'administrador' será possível utilizar as chaves. |
Faça Backup do seu diretório ~/.ssh/
Se você desinstalar o seu sistema e quer manter o par de chaves que foram geradas, faça backup do diretório |
Generating Key Pairs To generate an RSA key pair for version 2 of the SSH protocol, follow these steps:
-
Gerar uma par de chaves RSA digitando os seguintes em seu terminal:
~]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/USER/.ssh/id_rsa):
-
Digite Enter para confirmar a localização padrão,
~/.ssh/id_rsa
, para as chaves criadas recentemente. -
Entre com a frase de acesso, e confirme entrando novamente quando o terminal solicitar. Por razões de segurança, evite utilizar a mesma senha que usa na sua conta de acesso.
Depois disso, você irá ser presenteado com uma mensagem similar a essa:
Your identification has been saved in /home/USER/.ssh/id_rsa. Your public key has been saved in /home/USER/.ssh/id_rsa.pub. The key fingerprint is: e7:97:c7:e2:0e:f9:0e:fc:c4:d7:cb:e5:31:11:92:14 USER@penguin.example.com The key's randomart image is: +--[ RSA 2048]----+ | E. | | . . | | o . | | . .| | S . . | | + o o ..| | * * +oo| | O +..=| | o* o.| +-----------------+
-
By default, the permissions of the
~/.ssh/
directory are set torwx------
or700
expressed in octal notation. This is to ensure that only the USER can view the contents. If required, this can be confirmed with the following command:~]$ ls -ld ~/.ssh drwx------. 2 USER USER 54 Nov 25 16:56 /home/USER/.ssh/
-
Para copiar a chave pública para uma máquina remota, forneça um comando no seguinte formato:
ssh-copy-id user@hostname
Isso vai copiar a modificação a mais recente chave pública em
~/.ssh/id*.pub
se isso não estiver instalado ainda. Alternativamente especifique o nome do arquivo da chave pública como o seguinte:ssh-copy-id -i ~/.ssh/id_rsa.pub user@hostname
This will copy the content of
~/.ssh/id_rsa.pub
into the~/.ssh/authorized_keys
file on the machine to which you want to connect. If the file already exists, the keys are appended to its end.
To generate an ECDSA key pair for version 2 of the SSH protocol, follow these steps:
-
Generate an ECDSA key pair by typing the following at a shell prompt:
~]$ ssh-keygen -t ecdsa Generating public/private ecdsa key pair. Enter file in which to save the key (/home/USER/.ssh/id_ecdsa):
-
Press Enter to confirm the default location,
~/.ssh/id_ecdsa
, for the newly created key. -
Entre com a frase de acesso, e confirme entrando novamente quando o terminal solicitar. Por razões de segurança, evite utilizar a mesma senha que usa na sua conta de acesso.
Depois disso, você irá ser presenteado com uma mensagem similar a essa:
Your identification has been saved in /home/USER/.ssh/id_ecdsa. Your public key has been saved in /home/USER/.ssh/id_ecdsa.pub. The key fingerprint is: fd:1d:ca:10:52:96:21:43:7e:bd:4c:fc:5b:35:6b:63 USER@penguin.example.com The key's randomart image is: +--[ECDSA 256]---+ | .+ +o | | . =.o | | o o + ..| | + + o +| | S o o oE.| | + oo+.| | + o | | | | | +-----------------+
-
By default, the permissions of the
~/.ssh/
directory are set torwx------
or700
expressed in octal notation. This is to ensure that only the USER can view the contents. If required, this can be confirmed with the following command:~]$ ls -ld ~/.ssh ~]$ ls -ld ~/.ssh/ drwx------. 2 USER USER 54 Nov 25 16:56 /home/USER/.ssh/
-
Para copiar a chave pública para uma máquina remota, forneça um comando no seguinte formato:
ssh-copy-id USER@hostname
Isso vai copiar a modificação a mais recente chave pública em
~/.ssh/id*.pub
se isso não estiver instalado ainda. Alternativamente especifique o nome do arquivo da chave pública como o seguinte:ssh-copy-id -i ~/.ssh/id_ecdsa.pub USER@hostname
This will copy the content of
~/.ssh/id_ecdsa.pub
into the~/.ssh/authorized_keys
on the machine to which you want to connect. If the file already exists, the keys are appended to its end.
See Configuring ssh-agent for information on how to set up your system to remember the passphrase.
Never share your private key
The private key is for your personal use only, and it is important that you never give it to anyone. |
Configuring ssh-agent To store your passphrase so that you do not have to enter it each time you initiate a connection with a remote machine, you can use the ssh-agent authentication agent.
To save your passphrase for a certain shell prompt, use the following command:
~]$ ssh-add Enter passphrase for /home/USER/.ssh/id_rsa:
Note that when you log out, your passphrase will be forgotten. You must execute the command each time you log in to a virtual console or a terminal window.
Using OpenSSH Certificate Authentication
Introduction to SSH Certificates
Using public key cryptography for authentication requires copying the public key from every client to every server that the client intends to log into. This system does not scale well and can be an administrative burden. Using a public key from a certificate authority (CA) to authenticate client certificates removes the need to copy keys between multiple systems. While the X.509 Public Key Infrastructure Certificate system provides a solution to this issue, there is a submission and validation process, with associated fees, to go through in order to get a certificate signed. As an alternative, OpenSSH supports the creation of simple certificates and associated CA infrastructure.
OpenSSH certificates contain a public key, identity information, and validity constraints. They are signed with a standard SSH public key using the ssh-keygen utility. The format of the certificate is described in /usr/share/doc/openssh-version/PROTOCOL.certkeys
.
The ssh-keygen utility supports two types of certificates: user and host. User certificates authenticate users to servers, whereas host certificates authenticate server hosts to users. For certificates to be used for user or host authentication, sshd
must be configured to trust the CA public key.
Support for SSH Certificates
Support for certificate authentication of users and hosts using the new OpenSSH certificate format was introduced in Fedora 13, in the openssh-5.4p1-1.fc13 package. If required, to ensure the latest OpenSSH package is installed, enter the following command as root
:
~]# dnf install openssh Last metadata expiration check performed 0:58:01 ago on Sun Sep 6 16:07:22 2015. Package openssh-7.1p1-1.fc23.x86_64 is already installed, skipping.
Creating SSH CA Certificate Signing Keys
Two types of certificates are required, host certificates and user certificates. It is considered better to have two separate keys for signing the two certificates, for example ca_user_key
and ca_host_key
, however it is possible to use just one CA key to sign both certificates. It is also easier to follow the procedures if separate keys are used, so the examples that follow will use separate keys.
The basic format of the command to sign user’s public key to create a user certificate is as follows:
ssh-keygen -s ca_user_key -I certificate_ID id_rsa.pub
Where -s
indicates the private key used to sign the certificate, -I
indicates an identity string, the certificate_ID, which can be any alpha numeric value. It is stored as a zero terminated string in the certificate. The certificate_ID is logged whenever the certificate is used for identification and it is also used when revoking a certificate. Having a long value would make logs hard to read, therefore using the host name for host certificates and the user name for user certificates is a safe choice.
To sign a host’s public key to create a host certificate, add the -h
option:
ssh-keygen -s ca_host_key -I certificate_ID -h ssh_host_rsa_key.pub
Host keys are generated on the system by default, to list the keys, enter a command as follows:
~]# ls -l /etc/ssh/ssh_host* -rw-------. 1 root root 668 Jul 9 2014 /etc/ssh/ssh_host_dsa_key -rw-r--r--. 1 root root 590 Jul 9 2014 /etc/ssh/ssh_host_dsa_key.pub -rw-------. 1 root root 963 Jul 9 2014 /etc/ssh/ssh_host_key -rw-r--r--. 1 root root 627 Jul 9 2014 /etc/ssh/ssh_host_key.pub -rw-------. 1 root root 1671 Jul 9 2014 /etc/ssh/ssh_host_rsa_key -rw-r--r--. 1 root root 382 Jul 9 2014 /etc/ssh/ssh_host_rsa_key.pub
It is recommended to create and store CA keys in a safe place just as with any other private key. In these examples the |
-
On the server designated to be the CA, generate two keys for use in signing certificates. These are the keys that all other hosts need to trust. Choose suitable names, for example
ca_user_key
andca_host_key
. To generate the user certificate signing key, enter the following command asroot
:~]# ssh-keygen -t rsa -f ~/.ssh/ca_user_key Generating public/private rsa key pair. Created directory '/root/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/ca_user_key. Your public key has been saved in /root/.ssh/ca_user_key.pub. The key fingerprint is: 11:14:2f:32:fd:5d:f5:e4:7a:5a:d6:b6:a0:62:c9:1f root@host_name.example.com The key's randomart image is: +--[ RSA 2048]----+ | .+. o| | . o +.| | o + . . o| | o + . . ..| | S . ... *| | . . . .*.| | = E .. | | . o . | | . | +-----------------+
Generate a host certificate signing key,
ca_host_key
, as follows:~]# ssh-keygen -t rsa -f ~/.ssh/ca_host_key Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/ca_host_key. Your public key has been saved in /root/.ssh/ca_host_key.pub. The key fingerprint is: e4:d5:d1:4f:6b:fd:a2:e3:4e:5a:73:52:91:0b:b7:7a root@host_name.example.com The key's randomart image is: +--[ RSA 2048]----+ | .. | | . ....| | . . o +oo| | o . o *o| | S = .| | o. .| | *.E. | | +o= | | .oo. | +-----------------+
If required, confirm the permissions are correct:
~]# ls -la ~/.ssh total 40 drwxrwxrwx. 2 root root 4096 May 22 13:18 . dr-xr-x---. 3 root root 4096 May 8 08:34 .. -rw-------. 1 root root 1743 May 22 13:15 ca_host_key -rw-r--r--. 1 root root 420 May 22 13:15 ca_host_key.pub -rw-------. 1 root root 1743 May 22 13:14 ca_user_key -rw-r--r--. 1 root root 420 May 22 13:14 ca_user_key.pub -rw-r--r--. 1 root root 854 May 8 05:55 known_hosts -r--------. 1 root root 1671 May 6 17:13 ssh_host_rsa -rw-r--r--. 1 root root 1370 May 7 14:30 ssh_host_rsa-cert.pub -rw-------. 1 root root 420 May 6 17:13 ssh_host_rsa.pub
-
Create the CA server’s own host certificate by signing the server’s host public key together with an identification string such as the host name, the CA server’s fully qualified domain name (FQDN) but without the trailing
.
, and a validity period. The command takes the following form:ssh-keygen -s ~/.ssh/ca_host_key -I certificate_ID -h -n host_name.example.com -V -start:+end /etc/ssh/ssh_host_rsa.pub
The
-n
option restricts this certificate to a specific host within the domain. The-V
option is for adding a validity period; this is highly recommend. Where the validity period is intended to be one year, fifty two weeks, consider the need for time to change the certificates and any holiday periods around the time of certificate expiry.Por exemplo:
~]# ssh-keygen -s ~/.ssh/ca_host_key -I host_name -h -n host_name.example.com -V -1w:+54w5d /etc/ssh/ssh_host_rsa.pub Enter passphrase: Signed host key /root/.ssh/ssh_host_rsa-cert.pub: id "host_name" serial 0 for host_name.example.com valid from 2015-05-15T13:52:29 to 2016-06-08T13:52:29
Distributing and Trusting SSH CA Public Keys
Hosts that are to allow certificate authenticated log in from users must be configured to trust the CA’s public key that was used to sign the user certificates, in order to authenticate user’s certificates. In this example that is the ca_user_key.pub
.
Publish the ca_user_key.pub
key and download it to all hosts that are required to allow remote users to log in. Alternately, copy the CA user public key to all the hosts. In a production environment, consider copying the public key to an administrator account first. The secure copy command can be used to copy the public key to remote hosts. The command has the following format:
scp ~/.ssh/ca_user_key.pub root@host_name.example.com:/etc/ssh/
Where host_name is the host name of a server the is required to authenticate user’s certificates presented during the login process. Ensure you copy the public key not the private key. For example, as root
:
~]# scp ~/.ssh/ca_user_key.pub root@host_name.example.com:/etc/ssh/ The authenticity of host 'host_name.example.com (10.34.74.56)' can't be established. RSA key fingerprint is fc:23:ad:ae:10:6f:d1:a1:67:ee:b1:d5:37:d4:b0:2f. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'host_name.example.com,10.34.74.56' (RSA) to the list of known hosts. root@host_name.example.com's password: ca_user_key.pub 100% 420 0.4KB/s 00:00
For remote user authentication, CA keys can be marked as trusted per-user in the ~/.ssh/authorized_keys
file using the cert-authority directive or for global use by means of the TrustedUserCAKeys directive in the /etc/ssh/sshd_config
file. For remote host authentication, CA keys can be marked as trusted globally in the /etc/ssh/known_hosts
file or per-user in the ~/.ssh/ssh_known_hosts
file.
-
For user certificates which have one or more principles listed, and where the setting is to have global effect, edit the
/etc/ssh/sshd_config
file as follows:TrustedUserCAKeys /etc/ssh/ca_user_key.pub
Restart
sshd
to make the changes take effect:~]# service sshd restart
To avoid being presented with the warning about an unknown host, a user’s system must trust the CA’s public key that was used to sign the host certificates. In this example that is ca_host_key.pub
.
-
Extract the contents of the public key used to sign the host certificate. For example, on the CA:
cat ~/.ssh/ca_host_key.pub ssh-rsa AAAAB5Wm.== root@ca-server.example.com
-
To configure client systems to trust servers' signed host certificates, add the contents of the
ca_host_key.pub
into the globalknown_hosts
file. This will automatically check a server’s host advertised certificate against the CA public key for all users every time a new machine is connected to in the domain*.example.com
. Login asroot
and configure the/etc/ssh/ssh_known_hosts
file, as follows:~]# vi /etc/ssh/ssh_known_hosts # A CA key, accepted for any host in *.example.com @cert-authority *.example.com ssh-rsa AAAAB5Wm.
Where
ssh-rsa AAAAB5Wm.
is the contents ofca_host_key.pub
. The above configures the system to trust the CA servers host public key. This enables global authentication of the certificates presented by hosts to remote users.
Creating SSH Certificates
A certifcate is a signed public key. The user’s and host’s public keys must be copied to the CA server for signing by the CA server’s private key.
Copying many keys to the CA to be signed can create confusion if they are not uniquely named. If the default name is always used then the latest key to be copied will overwrite the previously copied key, which may be an acceptable method for one administrator. In the example below the default name is used. In a production environment, consider using easily recognizable names. It is recommend to have a designated directory on the CA server owned by an administrative user for the keys to be copied into. Copying these keys to the |
Create an administrator account, in this example admin
, and a directory to receive the user’s keys. For example:
~]$ mkdir keys
Set the permissions to allow keys to be copied in:
~]$ chmod o+w keys ls -la keys total 8 drwxrwxrwx. 2 admin admin 4096 May 22 16:17 . drwx------. 3 admin admin 4096 May 22 16:17 ..
Creating SSH Certificates to Authenticate Hosts
The command to sign a host certificate has the following format:
ssh-keygen -s ca_host_key -I host_name -h ssh_host_rsa_key.pub
The host certificate will named ssh_host_rsa_key-cert.pub
.
To authenticate a host to a user, a public key must be generated on the host, passed to the CA server, signed by the CA, and then passed back to be stored on the host to present to a user attempting to log into the host.
-
Host keys are generated automatically on the system. To list them enter the following command:
~]# ls -l /etc/ssh/ssh_host* -rw-------. 1 root root 668 May 6 14:38 /etc/ssh/ssh_host_dsa_key -rw-r--r--. 1 root root 590 May 6 14:38 /etc/ssh/ssh_host_dsa_key.pub -rw-------. 1 root root 963 May 6 14:38 /etc/ssh/ssh_host_key -rw-r--r--. 1 root root 627 May 6 14:38 /etc/ssh/ssh_host_key.pub -rw-------. 1 root root 1679 May 6 14:38 /etc/ssh/ssh_host_rsa_key -rw-r--r--. 1 root root 382 May 6 14:38 /etc/ssh/ssh_host_rsa_key.pub
-
Copy the chosen public key to the server designated as the CA. For example, from the host:
~]# scp /etc/ssh/ssh_host_rsa_key.pub admin@ca-server.example.com:~/keys/ssh_host_rsa_key.pub The authenticity of host 'ca-server.example.com (10.34.74.58)' can't be established. RSA key fingerprint is b0:e5:ea:b8:75:e2:f0:b1:fe:5b:07:39:7f:58:64:d9. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'ca-server.example.com,10.34.74.58' (RSA) to the list of known hosts. admin@ca-server.example.com's password: ssh_host_rsa_key.pub 100% 382 0.4KB/s 00:00
Alternately, from the CA:
~]$ scp root@host_name.example.com:/etc/ssh/ssh_host_rsa_key.pub ~/keys/ssh_host_rsa_key.pub
-
On the CA server, sign the host’s public key. For example, as
root
:~]# ssh-keygen -s ~/.ssh/ca_host_key -I host_name -h -n host_name.example.com -V -1d:+54w /home/admin/keys/ssh_host_rsa_key.pub Enter passphrase: Signed host key /home/admin/keys/ssh_host_rsa_key-cert.pub: id "host_name" serial 0 for host_name.example.com valid from 2015-05-26T12:21:54 to 2016-06-08T12:21:54
Where host_name is the host name of the system requiring the certificate.
-
Copy the certificate to the host. For example, from the CA:
~]# scp /home/admin/keys/ssh_host_rsa_key-cert.pub root@host_name.example.com:/etc/ssh/ root@host_name.example.com's password: ssh_host_rsa_key-cert.pub 100% 1384 1.5KB/s 00:00
-
Configure the host to present the certificate to a user’s system when a user initiates the login process. As
root
, edit the/etc/ssh/sshd_config
file as follows:HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub
-
Restart
sshd
to make the changes take effect:~]# service sshd restart
-
On user’s systems. remove keys belonging to hosts from the
~/.ssh/known_hosts
file if the user has previously logged into the host configured above. When a user logs into the host they should no longer be presented with the warning about the hosts authenticity.
To test the host certificate, on a client system, ensure the client has set up the global /etc/ssh/known_hosts
file, as described in Trusting the Host Signing Key, and that the server’s public key is not in the ~/.ssh/known_hosts
file. Then attempt to log into the server over SSH as a remote user. You should not see a warning about the authenticity of the host. If required, add the -v
option to the SSH command to see logging information.
Creating SSH Certificates for Authenticating Users
To sign a user’s certificate, use a command in the following format:
ssh-keygen -s ca_user_key -I user_name -n user_name -V -start:+end id_rsa.pub
The resulting certificate will be named id_rsa-cert.pub
.
The default behavior of OpenSSH is that a user is allowed to log in as a remote user if one of the principals specified in the certificate matches the remote user’s name. This can be adjusted in the following ways:
-
Add more user’s names to the certificate during the signing process using the
-n
option:-n "name1[,name2,...]"
-
On the user’s system, add the public key of the CA in the
~/.ssh/authorized_keys
file using the cert-authority directive and list the principals names as follows:~]# vi ~/.ssh/authorized_keys # A CA key, accepted for any host in *.example.com @cert-authority principals="name1,name2" *.example.com ssh-rsa AAAAB5Wm.
-
On the server, create an
AuthorizedPrincipalsFile
file, either per user or glabally, and add the principles' names to the file for those users allowed to log in. Then in the/etc/ssh/sshd_config
file, specify the file using the AuthorizedPrincipalsFile directive.
To authenticate a user to a remote host, a public key must be generated by the user, passed to the CA server, signed by the CA, and then passed back to be stored by the user for use when logging in to a host.
-
On client systems, login as the user who requires the certificate. Check for available keys as follows:
~]$ ls -l ~/.ssh/
If no suitable public key exists, generate one and set the directory permissions if the directory is not the default directory. For example, enter the following command:
~]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/user1/.ssh/id_rsa): Created directory '/home/user1/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user1/.ssh/id_rsa. Your public key has been saved in /home/user1/.ssh/id_rsa.pub. The key fingerprint is: b1:f8:26:a7:46:87:c3:60:54:a3:6d:85:0d:60:fe:ce user1@host1.example.com The key's randomart image is: +--[ RSA 2048]----+ | oo++. | | o.o.o. | | .o o . | | oo . o | | . oo.S | | o=.. | | .Eo+ | | .= | | .. | +-----------------+
By default the directory permissions for a user’s keys are
drwx------.
, or octal 0700. If required, confirm the permissions are correct:~]$ ls -la ~/.ssh total 16 drwx------. 2 user1 user1 4096 May 7 12:37 . drwx------. 3 user1 user1 4096 May 7 12:37 .. -rw-------. 1 user1 user1 1679 May 7 12:37 id_rsa -rw-r--r--. 1 user1 user1 421 May 7 12:37 id_rsa.pub
See Using Key-based Authentication for more examples of key generation and for instructions on setting the correct directory permissions.
-
The chosen public key must be copied to the server designated as the CA, in order to be signed. The secure copy command can be used to do this, the command has the following format:
scp ~/.ssh/id_protocol.pub admin@ca_server.example.com:~/keys/
Where protocol is the part of the file name indicating the protocol used to generate the key, for example
rsa
, admin is an account on the CA server, and /keys/ is a directory setup to receive the keys to be signed.Copy the chosen public key to the server designated as the CA. For example:
~]$ scp ~/.ssh/id_rsa.pub admin@ca-server.example.com:~/keys/ admin@ca-server.example.com's password: id_rsa.pub 100% 421 0.4KB/s 00:00
If you have configured the client system to trust the host signing key as described in Trusting the Host Signing Key then you should not see a warning about the authenticity of the remote host.
-
On the CA server, sign the user’s public key. For example, as
root
:~]# ssh-keygen -s ~/.ssh/ca_user_key -I user1 -n user1 -V -1d:+54w /home/admin/keys/id_rsa.pub Enter passphrase: Signed user key /home/admin/keys/id_rsa-cert.pub: id "user1" serial 0 for host_name.example.com valid from 2015-05-21T16:43:17 to 2016-06-03T16:43:17
-
Copy the resulting certificate to the user’s
~/.ssh/
directory on their system. For example:~]# scp /home/admin/keys/id_rsa-cert.pub user1@host_name.example.com:~/.ssh/ user1@host_name.example.com's password: id_rsa-cert.pub 100% 1498 1.5KB/s 00:00
-
If using the standard file names and location then no further configuration is required as the SSH daemon will search for user certificates ending in
-cert.pub
and use them automatically if it finds them. Note that the default location and file names for for SSH version 2 keys are:~/.ssh/id_dsa
,~/.ssh/id_ecdsa
and~/.ssh/id_rsa
as explained in thessh_config(5)
manual page. If you use these locations and naming conventions then there is no need for editing the configuration files to enablesshd
to present the certificate. They will be used automatically when logging in to a remote system. In this is the case then skip to step 6.If required to use a non-default directory or file naming convention, then as
root
, add the following line to the/etc/ssh/ssh_config
or~/.ssh/config
files:IdentityFile ~/path/key_file
Note that this must be the private key name, do not had
.pub
or-cert.pub
. Ensure the file permission are correct. For example:~]$ ls -la ~/.ssh/config -rw-rw-r--. 1 user1 user1 36 May 27 21:49 /home/user1/.ssh/config chmod 700 ~/.ssh/config ~]$ ls -la ~/.ssh/config -rwx------. 1 user1 user1 36 May 27 21:49 /home/user1/.ssh/config
This will enable the user of this system to be authenticated by a user certificate when logging into a remote system configured to trust the CA user certificate signing key.
-
To test the user certificate, attempt to log into a server over SSH from the user’s account. You should do this as the user listed as a principle in the certificate, if any are specified. You should not be prompted for a password. If required, add the
-v
option to the SSH command to see logging information.
Signing an SSH Certificate Using a PKCS#11 Token
It is possible to sign a host key using a CA key stored in a PKCS#11 token by providing the token library using the -D
and identifying the CA key by providing its public half as an argument to the -s
option:
ssh-keygen -s ca_host_key.pub -D libpkcs11.so -I certificate_ID host_key.pub
In all cases, certificate_ID is a "key identifier" that is logged by the server when the certificate is used for authentication.
Certificates may be configured to be valid only for a set of users or host names, the principals. By default, generated certificates are valid for all users or hosts. To generate a certificate for a specified set of principals, use a comma separated list with the -n
option as follows:
ssh-keygen -s ca_user_key.pub -D libpkcs11.so -I certificate_ID -n user1,user2 id_rsa.pub
and for hosts:
ssh-keygen -s ca_host_key.pub -D libpkcs11.so -I certificate_ID -h -n host.domain ssh_host_rsa_key.pub
Additional limitations on the validity and use of user certificates may be specified through certificate options. A certificate option may disable features of the SSH session, may be valid only when presented from particular source addresses or may force the use of a specific command. For a list of valid certificate options, see the ssh-keygen(1)
manual page for the -O
option.
Certificates may be defined to be valid for a specific lifetime. The -V
option allows specifying a certificates start and end times. For example:
ssh-keygen -s ca_user_key -I certificate_ID id_rsa.pub -V "-1w:+54w5d"
A certificate that is presented at a time outside this range will not be considered valid. By default, certificates are valid indefinitely starting from UNIX Epoch.
Viewing an SSH CA Certificate
To view a certificate, use the -L
to list the contents. For example, for a user’s certificate:
~]$ ssh-keygen -L -f ~/.ssh/id_rsa-cert.pub /home/user1/.ssh/id_rsa-cert.pub: Type: ssh-rsa-cert-v01@openssh.com user certificate Public key: RSA-CERT 3c:9d:42:ed:65:b6:0f:18:bf:52:77:c6:02:0e:e5:86 Signing CA: RSA b1:8e:0b:ce:fe:1b:67:59:f1:74:cd:32:af:5f:c6:e8 Key ID: "user1" Serial: 0 Valid: from 2015-05-27T00:09:16 to 2016-06-09T00:09:16 Principals: user1 Critical Options: (none) Extensions: permit-X11-forwarding permit-agent-forwarding permit-port-forwarding permit-pty permit-user-rc
To vew a host certificate:
~]# ssh-keygen -L -f /etc/ssh/ssh_host_rsa_key-cert.pub /etc/ssh/ssh_host_rsa_key-cert.pub: Type: ssh-rsa-cert-v01@openssh.com host certificate Public key: RSA-CERT 1d:71:61:50:05:9b:ec:64:34:27:a5:cc:67:24:03:23 Signing CA: RSA e4:d5:d1:4f:6b:fd:a2:e3:4e:5a:73:52:91:0b:b7:7a Key ID: "host_name" Serial: 0 Valid: from 2015-05-26T17:19:01 to 2016-06-08T17:19:01 Principals: host_name.example.com Critical Options: (none) Extensions: (none)
Revoking an SSH CA Certificate
If a certificate is stolen, it should be revoked. Although OpenSSH does not provide a mechanism to distribute the revocation list it is still easier to create the revocation list and distribute it by other means then to change the CA keys and all host and user certificates previously created and distributed.
Keys can be revoked by adding them to the revoked_keys
file and specifying the file name in the sshd_config
file as follows:
RevokedKeys /etc/ssh/revoked_keys
Note that if this file is not readable, then public key authentication will be refused for all users.
A new key revocation list can be generated as follows:
~]$ ssh-keygen -kf /etc/ssh/revoked_keys -z 1 ~/.ssh/id_rsa.pub
To add lines to the list, use the -u
option to update the list:
ssh-keygen -ukf /etc/ssh/revoked_keys -z integer ~/.ssh/id_rsa.pub
where integer is the line number.
To test if a key has been revoked, query the revocation list for the presence of the key. Use a command as follows:
ssh-keygen -Qf /etc/ssh/revoked_keys ~/.ssh/id_rsa.pub
A user can revoke a CA certificate by changing the cert-authority directive to revoke in the known_hosts
file.
OpenSSH Clients
Tenha certeza que possui pacotes relevantes instalados
To connect to an OpenSSH server from a client machine, you must have the openssh-clients package installed. See Installing Packages for more information on how to install new packages in Fedora 26. |
Using the ssh Utility
The ssh utility allows you to log in to a remote machine and execute commands there. It is a secure replacement for the rlogin, rsh, and telnet programs.
Similarly to the telnet command, log in to a remote machine by using the following command:
ssh hostname
For example, to log in to a remote machine named penguin.example.com
, type the following at a shell prompt:
~]$ ssh penguin.example.com
This will log you in with the same user name you are using on the local machine. If you want to specify a different user name, use a command in the following form:
ssh username@hostname
For example, to log in to penguin.example.com
as USER
, type:
~]$ ssh USER@penguin.example.com
The first time you initiate a connection, you will be presented with a message similar to this:
The authenticity of host 'penguin.example.com' can't be established. ECDSA key fingerprint is 256 da:24:43:0b:2e:c1:3f:a1:84:13:92:01:52:b4:84:ff. Are you sure you want to continue connecting (yes/no)?
Users should always check if the fingerprint is correct before answering the question in this dialog. The user can ask the administrator of the server to confirm the key is correct. This should be done in a secure and previously agreed way. If the user has access to the server’s host keys, the fingerprint can be checked by using the ssh-keygen command as follows:
~]# ssh-keygen -l -f /etc/ssh/ssh_host_ecdsa_key.pub 256 da:24:43:0b:2e:c1:3f:a1:84:13:92:01:52:b4:84:ff (ECDSA)
Type yes
to accept the key and confirm the connection. You will see a notice that the server has been added to the list of known hosts, and a prompt asking for your password:
Warning: Permanently added 'penguin.example.com' (ECDSA) to the list of known hosts. USER@penguin.example.com's password:
Updating the host key of an SSH server
If the SSH server’s host key changes, the client notifies the user that the connection cannot proceed until the server’s host key is deleted from the To remove a key from the ~]# ssh-keygen -R penguin.example.com # Host penguin.example.com found: line 15 type ECDSA /home/USER/.ssh/known_hosts updated. Original contents retained as /home/USER/.ssh/known_hosts.old |
After entering the password, you will be provided with a shell prompt for the remote machine.
Alternatively, the ssh program can be used to execute a command on the remote machine without logging in to a shell prompt:
ssh username@hostname command
For example, the /etc/redhat-release
file provides information about the Fedora version. To view the contents of this file on penguin.example.com
, type:
~]$ ssh USER@penguin.example.com cat /etc/redhat-release USER@penguin.example.com's password: Fedora release 20 (Heisenbug)
After you enter the correct password, the user name will be displayed, and you will return to your local shell prompt.
Using the scp Utility
scp can be used to transfer files between machines over a secure, encrypted connection. In its design, it is very similar to rcp.
To transfer a local file to a remote system, use a command in the following form:
scp localfile username@hostname:remotefile
For example, if you want to transfer taglist.vim
to a remote machine named penguin.example.com
, type the following at a shell prompt:
~]$ scp taglist.vim USER@penguin.example.com:.vim/plugin/taglist.vim USER@penguin.example.com's password: taglist.vim 100% 144KB 144.5KB/s 00:00
Multiple files can be specified at once. To transfer the contents of .vim/plugin/
to the same directory on the remote machine penguin.example.com
, type the following command:
~]$ scp .vim/plugin/* USER@penguin.example.com:.vim/plugin/ USER@penguin.example.com's password: closetag.vim 100% 13KB 12.6KB/s 00:00 snippetsEmu.vim 100% 33KB 33.1KB/s 00:00 taglist.vim 100% 144KB 144.5KB/s 00:00
To transfer a remote file to the local system, use the following syntax:
scp username@hostname:remotefile localfile
For instance, to download the .vimrc
configuration file from the remote machine, type:
~]$ scp USER@penguin.example.com:.vimrc .vimrc USER@penguin.example.com's password: .vimrc 100% 2233 2.2KB/s 00:00
Using the sftp Utility
The sftp utility can be used to open a secure, interactive FTP session. In its design, it is similar to ftp except that it uses a secure, encrypted connection.
To connect to a remote system, use a command in the following form:
sftp username@hostname
For example, to log in to a remote machine named penguin.example.com
with USER
as a user name, type:
~]$ sftp USER@penguin.example.com USER@penguin.example.com's password: Connected to penguin.example.com. sftp>
After you enter the correct password, you will be presented with a prompt. The sftp utility accepts a set of commands similar to those used by ftp (see A selection of available sftp commands).
Command | Description |
---|---|
ls [directory] |
List the content of a remote directory. If none is supplied, a current working directory is used by default. |
cd directory |
Change the remote working directory to directory. |
mkdir directory |
Create a remote directory. |
rmdir path |
Remove a remote directory. |
put localfile [remotefile] |
Transfer localfile to a remote machine. |
get remotefile [localfile] |
Transfer remotefile from a remote machine. |
For a complete list of available commands, see the sftp
(1) manual page.
More Than a Secure Shell
A secure command line interface is just the beginning of the many ways SSH can be used. Given the proper amount of bandwidth, X11 sessions can be directed over an SSH channel. Or, by using TCP/IP forwarding, previously insecure port connections between systems can be mapped to specific SSH channels.
X11 Forwarding
To open an X11 session over an SSH connection, use a command in the following form:
ssh -Y username@hostname
For example, to log in to a remote machine named penguin.example.com
with USER
as a user name, type:
~]$ ssh -Y USER@penguin.example.com USER@penguin.example.com's password:
When an X program is run from the secure shell prompt, the SSH client and server create a new secure channel, and the X program data is sent over that channel to the client machine transparently.
Note that the X Window system must be installed on the remote system before X11 forwarding can take place. Enter the following command as root
to install the X11 package group:
~]# dnf group install "X Window System"
X11 forwarding can be very useful. For example, X11 forwarding can be used to create a secure, interactive session of the Print Settings utility. To do this, connect to the server using ssh and type:
~]$ system-config-printer &
The Print Settings tool will appear, allowing the remote user to safely configure printing on the remote system.
Port Forwarding
SSH can secure otherwise insecure TCP/IP
protocols via port forwarding. When using this technique, the SSH server becomes an encrypted conduit to the SSH client.
Port forwarding works by mapping a local port on the client to a remote port on the server. SSH can map any port from the server to any port on the client. Port numbers do not need to match for this technique to work.
Using reserved port numbers
Setting up port forwarding to listen on ports below 1024 requires |
To create a TCP/IP port forwarding channel which listens for connections on the localhost
, use a command in the following form:
ssh -L local-port:remote-hostname:remote-port username@hostname
For example, to check email on a server called mail.example.com
using POP3
through an encrypted connection, use the following command:
~]$ ssh -L 1100:mail.example.com:110 mail.example.com
Once the port forwarding channel is in place between the client machine and the mail server, direct a POP3 mail client to use port 1100
on the localhost
to check for new email. Any requests sent to port 1100
on the client system will be directed securely to the mail.example.com
server.
If mail.example.com
is not running an SSH server, but another machine on the same network is, SSH can still be used to secure part of the connection. However, a slightly different command is necessary:
~]$ ssh -L 1100:mail.example.com:110 other.example.com
In this example, POP3 requests from port 1100
on the client machine are forwarded through the SSH connection on port 22
to the SSH server, other.example.com
. Then, other.example.com
connects to port 110
on mail.example.com
to check for new email. Note that when using this technique, only the connection between the client system and other.example.com
SSH server is secure.
Port forwarding can also be used to get information securely through network firewalls. If the firewall is configured to allow SSH traffic via its standard port (that is, port 22) but blocks access to other ports, a connection between two hosts using the blocked ports is still possible by redirecting their communication over an established SSH connection.
A connection is only as secure as a client system
Using port forwarding to forward connections in this manner allows any user on the client system to connect to that service. If the client system becomes compromised, the attacker also has access to forwarded services. System administrators concerned about port forwarding can disable this functionality on the server by specifying a |
Recursos adicionais
For more information on how to configure or connect to an OpenSSH server on Fedora, see the resources listed below.
-
sshd
(8) — The manual page for thesshd
daemon documents available command line options and provides a complete list of supported configuration files and directories. -
ssh
(1) — The manual page for the ssh client application provides a complete list of available command line options and supported configuration files and directories. -
scp
(1) — The manual page for the scp utility provides a more detailed description of this utility and its usage. -
sftp
(1) — The manual page for the sftp utility. -
ssh-keygen
(1) — The manual page for the ssh-keygen utility documents in detail how to use it to generate, manage, and convert authentication keys used by ssh. -
ssh_config
(5) — The manual page namedssh_config
documents available SSH client configuration options. -
sshd_config
(5) — The manual page namedsshd_config
provides a full description of available SSH daemon configuration options.
-
OpenSSH Home Page — The OpenSSH home page containing further documentation, frequently asked questions, links to the mailing lists, bug reports, and other useful resources.
-
OpenSSL Home Page — The OpenSSL home page containing further documentation, frequently asked questions, links to the mailing lists, and other useful resources.
Want to help? Learn how to contribute to Fedora Docs ›