SSH

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

SSH (Secure SHell) is the ubiquitous tool for logging into and working on remote machines securely. All sensitive information is strongly encrypted, and in addition to the remote shell, SSH supports file transfer, and port forwarding for arbitrary protocols, allowing secure access to remote services. It replaces the classic telnet, rlogin, and similar non-secure tools - but SSH is not just a remote shell, it is a complete environment for working with remote systems.

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

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

Установка

Проверка установки

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

user $ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
           [-i identity_file] [-J [user@]host[:port]] [-L address]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] destination [command]

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

USE-флаги

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

X Add support for X11
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
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)
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

После включения нужных USE-флагов не забудьте установить (или пересобрать) OpenSSH:

root #emerge --ask --changed-use --oneshot 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

Конфигурация

Создание ключей

Работа безопасной оболочки в SSH основана на использовании криптографических ключей, применяемых для шифрования, дешифрования и хэширования.

Системные ключи генерируются при первом запуске службы SSH. Ключи можно сгенерировать заново с помощью команды ssh-keygen.

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

Настройка сервера

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

sshd_config.

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

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

Настройка клиента

Клиент ssh и относящиеся к нему программы (scp, sftp и другие) настраиваются в следующих файлах:

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

Для более детальной информации прочтите документацию для ssh_config.

Предотвращение вторжений

SSH — это служба, которая часто подвергается атаке. Некоторые инструменты (например, sshguard и fail2ban) отслеживают логи и заносят в чёрный список удаленных пользователей после нескольких неудачных попыток войти в систему. Использование подобных программ необходимо для укрепления защиты систем, подвергающихся частым атакам.

Сервисы

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

OpenRC

Добавьте OpenSSH демон в уровень запуска default:

root #rc-update add sshd default

Запустим службу sshd с помощью команды:

root #rc-service sshd start

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

root #rc-service sshd start
root #rc-service sshd stop
root #rc-service sshd restart
Заметка
Активные SSH подключения к серверу не обрываются при вводе команды rc-service sshd restart.

systemd

Для того чтобы демон OpenSSH загружался при запуске системы:

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

Для запуска OpenSSH демона:

root #systemctl start sshd.service

Для проверки работает ли сервис:

root #systemctl status sshd.service

Использование

Команды

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

Управляющие последовательности

В процессе сессии SSH, нажатие кнопки "тильда" (~) начинает управляющую последовательность. Введите следующее для списка опций:

ssh>~?

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

Подключение к удалённому серверу SSH

Полезна для работы с git-сервером.

Клиент

На стороне клиента, если это ещё не сделано, создайте пару ключей. Это можно сделать, запустив следующую команду (конечно, не вводя парольной фразы):

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.. .. ..       |
| :. .  ! .       |
+-----------------+

Сервер

Проверьте, что аккаунт пользователя существует на сервере, затем поместите содержимое клиентского файла id_rsa.pub в файл ~/.ssh/authorized_keys, расположенный в домашнем каталоге пользователя. Это можно сделать, запустив следующую команду на компьютере-клиенте (тут необходимо ввести пароль пользователя):

user $ssh-copy-id <server>
/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: 

Number of key(s) added: 1

Теперь попробуйте войти в машину с помощью "ssh '<server>'" и убедитесь, что только желаемые вами ключи были добавлены.

После этого должен быть возможен вход без пароля:

user $ssh <server>
larry@<server>

После этого на сервере в файле /etc/ssh/sshd_config должно быть PasswordAuthentication no.

Проверка на одной машине

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

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

Remote services over ssh

SSH may be used to access remote services, such as HTTP, HTTPS, fileshares, etc., through an encrypted "tunnel". Remote service access is detailed in the SSH tunneling and SSH jump host articles.

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.

Заметка
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.".

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, 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 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 the 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

Tips

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.

SSH over intermittent connections

When on unstable Internet connections, or when roaming between networks (such as when moving wifi networks), mosh can help avoid dropping SSH sessions.

Open new tabs for session with Kitty terminal

By using the SSH kitten for the Kitty terminal emulator, it is possible to open new "tabs", or windows, on the current SSH session without having log in again.

Kitty also provides other practical SSH functionality.

Устранение проблем

Существует 3 различных уровня отладки. Параметр -v заставляет ssh выводить отладочные сообщения о своей работе. Это полезно при отладке соединения, проблемах аутентификации и настройки. Несколько параметров -v увеличивают подробность сообщений. Максимальный уровень подробности равен трём.

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.

Обрыв долгоживущих соединений

Многие устройства доступа к Интернету выполняют преобразование сетевых адресов (NAT). Это процесс, который позволяет устройствам из частной сети, которая обычно находится дома или на работе, получить доступ к другим сетям (например, к Интернету) не смотря на то, что для этой сети выделен только один IP-адрес. К сожалению, не все NAT-устройства одинаково устроены, и некоторые из них могут обрывать долгоживущие TCP-соединения, в том числе, используемые в SSH. Обычно это обнаруживается при внезапной потере возможности взаимодействия с удаленным сервером, хотя сама программа ssh свою работу не прекращала.

Чтобы решить данную проблему, можно настроить клиенты и сервера OpenSSH таким образом, чтобы они посылали незаметные сообщения «keep alive», нацеленные на поддержку и подтверждение использования соединения:

  • Чтобы включить поддержку keep alive для всех клиентов подключающихся к вашему локальному серверу установите в файле /etc/ssh/sshd_config параметр ClientAliveInterval 30 (или другое значение в секундах).
  • Чтобы включить поддержку keep alive для всех серверов подключенных к вашему локальному клиенту, установите в файле /etc/ssh/ssh_config параметр ServerAliveInterval 30 (или другое значение в секундах).

For example, to modify the server's configuration:

ФАЙЛ /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:

ФАЙЛ /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

New key does not get used

This scenario covers the case when a key to access a remote system has been created, the public key installed on the remote system, but the remote system is (for some reason) not accessible via ssh. This can happen if the name of the keyfile is not known to ssh.

Confirm which key files ssh is trying by running it with one of the verbose options, as described at the start of the Troubleshooting section. The verbose output will include the names of the keyfiles it is trying, and the one (if any) that actually gets used.

The default key files for the system are listed in the /etc/ssh/ssh_config, see the commented-out lines containing IdentityFile directives.

There are several ways to use a key with a non-default name.

The key name can be specified on the command line every time:

user $ssh -i ~/.ssh/my_keyfile user@remotesys

Alternatively, modify the ssh configuration to add a special case for ssh to the remote system:

ФАЙЛ /etc/ssh/ssh_configDefine keyfiles to use for host remotesys
Host remotesys
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/my_keyfile

If any are specified, it appears to be necessary to specify all the desired keys on a remote host. Read up on the ssh IdentityFile.

Проброс X11, но нет никакого проброса или туннелирования

Проблема: После того, как вы сделали необходимые изменения в файлах конфигурации, чтобы разрешить проброс X11, вы обнаруживаете, что приложения X запускаются на сервере, а не передаются клиенту.

Решение: Что скорее всего, в процессе входа через SSH на удаленный сервер или узел переменная DISPLAY либо сбрасывается, либо устанавливается после того, как её установит сеанс SSH.

Чтобы проверить этот вариант, послу удаленного входа выполните следующее:

user $echo $DISPLAY
localhost:10.0

Должно вывестись что-то похожее на localhost:10.0 или localhost2.local:10.0 (если на стороне сервера включён параметр X11UseLocalhost no). Если обычное «:0.0» не выводится, проверьте, что переменная DISPLAY не сбрасывается или не переинициализируется в файле $HOME/.bash_profile. Если это так, то удалите или закомментируйте инициализацию переменной DISPLAY, чтобы не дать командам в ~/.bash_profile выполниться в процессе входа SSH:

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

Не забудьте заменить larry в команде на подходящее имя пользователя.

Ещё одно решение — создать алиас в файле ~/.bashrc.

Смотрите также

Внешние ресурсы