SSH/ru

SSH (Secure SHell, безопасная оболочка) — это программа терминала, использующая шифрование, которая заменяет классическую программу telnet в Unix-подобных операционных системах.

В дополнение к удаленному терминальному доступу, предоставляемому основной программой ssh, в SSH был разработан набор программ, включающий в себя scp (Secure Copy Program, безопасное копирование) и sftp (Secure File Transfer Protocol, безопасный протокол передачи файлов).

Изначально SSH была не свободной программой. Однако сегодня самой популярной и де-факто стандартной версией SSH является реализация OpenSSH из операционной системы OpenBSD. Именно данная версия предустановлена на Gentoo.

Проверка установки
В большинстве развертываний Gentoo Linux пакет OpenSSH уже установлен в системе. Это можно проверить с помощью запуска команды ssh. Если пакет установлен, то будет отображена справка по использованию:

Если справка не будет отображена, то ssh либо испорчен, либо не установлен. Также возможно, что пользователь просто захочет пересобрать OpenSSH с новым набором USE-флагов. В любом случае, продолжим с обзора доступных USE.

Установка OpenSSH
After changing the necessary USE flags, do not forget to install (or rebuild) OpenSSH:

Сервер
Add openssh to the default runlevel if this has not been done already:

Start the sshd daemon with:

Сервер OpenSSH можно контролировать, как и любой другой сервис, контролируемый OpenRC:

Create keys
In order to provide a secure shell, cryptographic keys are used to manage the encryption, decryption, and hashing functionalities offered by SSH.

On the first start of the SSH service, system keys will be generated. Keys can be (re)generated using the ssh-keygen command.

To generate the key used for SSH protocol version 1 (which usually is not enabled anymore; it has been deprecated in favor of protocol version 2) use:

Для генерации ключей протокола SSH версии 2 (алгоритмы DSA и RSA):

Конфигурация сервера
Сервер SSH обычно конфигурируется в файле, хотя возможно провести дополнительную конфигурацию в файле OpenRC , включая изменение местоположения файла конфигурации. Для более детальной информации о том, как сконфигурировать сервер, смотри man-страницу sshd_config.

Users should study Sven's OpenSSH guide for a security focused configuration.

Конфигурация клиента
The ssh client and related programs (scp, sftp, etc.) can be configured using the following files:

For more information read the manual:

Беспарольная аутентификация
Полезна для работы с git сервером.

Клиент
На вашем клиенте запустите

Сервер
Make sure an account for the user exists on the server, and then place the clients' file into the server's  file in the user's home directory.

Single machine testing
Вышеописанную процедуру можно протестировать локально:

Если что-то пошло не так
There are 3 different levels of debug modes that can help troubleshooting issues. With the  option SSH prints debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple  options increase the verbosity. Maximum verbosity is three levels deep.

Death of long-lived connections
Many internet access devices perform Network Address Translation (NAT), a process that enables devices on a private network such as that typically found in a home or business place to access foreign networks, such as the internet, despite only having a single IP address on that network. Unfortunately, not all NAT devices are created equal, and some of them incorrectly close long-lived, occasional-use TCP connections such as those used by SSH. This is generally observable as a sudden inability to interact with the remote server, even though the ssh</tt> client program has not exited.

In order to resolve the issue, OpenSSH clients and servers can be configured to send a 'keep alive', or invisible message aimed at maintaining and confirming the live status of the link.
 * To enable keep alive for all clients connecting to your local server, set  (or some other value, in seconds) within the  file.
 * To enable keep alive for all servers connected to by your local client, set  (or some other value, in seconds) within the  file.

X11 forwarding, not forwarding, or tunneling
Problem: After having made the necessary changes to the configuration files for permitting X11 forwarding, it is discovered X applications are executing on the server and are not being forwarded to the client.

Solution: What is likely occurring during SSH login into the remote server or host, the  variable is either being unset or is being set after the SSH session sets it.

Test for this scenario perform the following after logging in remotely:

The output should be something similar to  or   using server side   setting. If the usual  is not displayed, check to make sure the   variable within  is not being unset or re-initializing. If it is, remove or comment out any custom initialization of  to prevent the code in  from executing during a SSH login:

A trick that works to complete this task would be to define an alias within the users' file.

Intrusion prevention
SSH is a commonly attacked service. Tools such as sshguard and fail2ban monitor logs and black list remote users who have repeatedly attempted, yet failed to login. Utilize them as needed to secure a frequently attacked system.

External resources

 * Securing OpenSSH - Gentoo developer documentation.
 * OpenSSH Key Management Part1 - Gentoo documentation, have a look at all 3 parts.