Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы

Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы Хостинг

С помощью защищенного протокола SSH администраторы подключаются к своим серверам для безопасной работы. Рассмотрим особенности этого протокола подробнее:

Статья в тему:
Как подключиться к серверу по SSH

Содержание
  1. Введение
  2. Introduction
  3. Что такое SSH-туннель?
  4. Что такое SFTP-протокол
  5. Generating and Working with SSH Keys
  6. Generating an SSH Key Pair
  7. Generate an SSH Key Pair with a Larger Number of Bits
  8. Removing or Changing the Passphrase on a Private Key
  9. Displaying the SSH Key Fingerprint
  10. Copying your Public SSH Key to a Server with SSH-Copy-ID
  11. Copying your Public SSH Key to a Server Without SSH-Copy-ID
  12. Copying your Public SSH Key to a Server Manually
  13. Отключение аутентификации по паролю
  14. Как работает SSH
  15. Этот материал был полезен?
  16. Client-Side Configuration Options
  17. Defining Server-Specific Connection Information
  18. Keeping Connections Alive to Avoid Timeout
  19. Disabling Host Checking
  20. Multiplexing SSH Over a Single TCP Connection
  21. Для чего используются SSH и SFTP протоколы
  22. Советы по настройке протокола SSH и дальнейшему применению
  23. Настройка SSH
  24. Опции для клиентской стороны
  25. Базовый синтаксис
  26. Using SSH Escape Codes to Control Connections
  27. Forcing a Disconnect from the Client-Side (How to Exit Out of a Stuck or Frozen Session)
  28. Placing an SSH Session into the Background
  29. Changing Port Forwarding Options on an Existing SSH Connection
  30. Setting Up SSH Tunnels
  31. Configuring Local Tunneling to a Server
  32. Configuring Remote Tunneling to a Server
  33. Configuring Dynamic Tunneling to a Remote Server
  34. Где найти доступы к серверу
  35. Как использовать протокол SSH?
  36. Какие есть SSH серверы?
  37. Клиенты и оболочки для SSH
  38. Server-Side Configuration Options
  39. Disabling Password Authentication
  40. Changing the Port that the SSH Daemon Runs On
  41. Limiting the Users Who can Connect Through SSH
  42. Disabling Root Login
  43. Forwarding X Application Displays to the Client
  44. Как подключиться к серверу по SSH с компьютера на Linux/MacOS
  45. Выполнение входа через SSH с использованием ключей
  46. Как работает аутентификация с помощью ключей?
  47. Создание ключей SSH
  48. Как передать ваш публичный ключ на сервер
  49. Как работает SSH?
  50. Basic Connection Instructions
  51. Running a Single Command on a Remote Server
  52. Logging in to a Server with a Different Port
  53. Adding your SSH Keys to an SSH Agent to Avoid Typing the Passphrase
  54. Forwarding your SSH Credentials to Use on a Server
  55. Выводы
  56. Заключение

Введение

Одним из важнейших инструментов в работе системного администратора является SSH.

SSH, или Secure Shell, — это протокол, используемый для безопасного входа на удаленные системы. Это самый распространенный способ получения доступа к удаленным серверам Linux.

В этом руководстве мы обсудим, как использовать SSH для подключения к удаленной системе.

Secure Shell ) используется для безопасного удалённого управления операционной системой. По SSH можно подключиться к любому серверу с операционной системой семейства Linux.

Если на вашем сервере установлена ОС Windows Server — используйте подключение по RDP.

Introduction

SSH is a secure protocol used as the primary means of connecting to Linux servers remotely. It provides a text-based interface by spawning a remote shell. After connecting, all commands you type in your local terminal are sent to the remote server and executed there.

In this cheat sheet-style guide, we will cover some common ways of connecting with SSH to achieve your objectives. This can be used as a quick reference when you need to know how to connect to or configure your server in different ways.

Что такое SSH-туннель?

Под данным термином подразумевается шифрование данных идущих по конкретному каналу (туннелю). Все данные шифруются на одном конце соединения, и дешифруются на другом. Благодаря этому, даже если они будут перехвачены третьими лицами, то злоумышленники не смогут ими воспользоваться.

Создание такого «туннеля», может проводиться по нескольким сценариям:

  • VPN-туннель. Данный способ можно использовать для любых приложений;
  • Специальные программы, что работают через SSH;
  • Socks-прокси;
  • При необходимости работать с определенным сервером, то есть вариант настройки соединения на нужный TCP-порт.

Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы

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

Поэтому, если вам нужно передать на сервер особо важные файлы, или воспользоваться удаленным доступом к операционной системе, то вполне логичным будет позаботиться о безопасности передачи данных. Сегодня, одним из наиболее распространенных способов защиты своих данных, является использование сетевого протокола SSH (Secure Shell).

Необходимость использования таких средств защиты обусловлена двумя факторами:

Давайте же разберемся, что же такое SSH, а также, как работает этот протокол?

Что такое SFTP-протокол

SFTP-протокол (от англ. SSH File Transfer Protocol) – сетевой протокол прикладного уровня, предназначенный для передачи файлов и других действий с ними через имеющееся надежное соединение. Протокол был разработан как расширение SSH-2, предназначенное для операций с файлами по защищенному каналу, однако может работать и с другими протоколами, обеспечивающими безопасное соединение сервера с клиентом. Иными словами, для надежной работы через SFTP-протокол необходимо иметь установленное защищенное соединение (например, SSH), которое проводит аутентификацию клиента и сервера и устанавливает факт их надежности, поскольку сам SFTP-протокол не проводит аутентификацию и не обеспечивает безопасность.

SFTP имеет ряд преимуществ перед своими предшественниками — FTP и SCP — таких, как прерывание передачи файла, удаление, возобновление передачи, связь переданных файлов с основными атрибутами, например, меткой даты/времени, а также более высокая платформонезависимость.

SFTP-протокол реализуется через SFTP-сервер и SFTP-клиент, которые являются подсистемами OpenSSH.

Generating and Working with SSH Keys

This section will cover how to generate SSH keys on a client machine and distribute the public key to servers where they should be used. This is a good section to start with if you have not previously generated keys due to the increased security that it allows for future connections.

Generating an SSH Key Pair

Generating a new SSH public and private key pair on your local computer is the first step towards authenticating with a remote server without a password. Unless there is a good reason not to, you should always authenticate using SSH keys.

A number of cryptographic algorithms can be used to generate SSH keys, including RSA, DSA, and ECDSA. RSA keys are generally preferred and are the default key type.

To generate an RSA key pair on your local computer, type:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/demo/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

The next prompt allows you to enter a passphrase of an arbitrary length to secure your private key. By default, you will have to enter any passphrase you set here every time you use the private key, as an additional security measure. Feel free to press ENTER to leave this blank if you do not want a passphrase. Keep in mind though that this will allow anyone who gains control of your private key to login to your servers.

If you choose to enter a passphrase, nothing will be displayed as you type. This is a security precaution.

Generate an SSH Key Pair with a Larger Number of Bits

SSH keys are 2048 bits by default. This is generally considered to be good enough for security, but you can specify a greater number of bits for a more hardened key.

To do this, include the -b argument with the number of bits you would like. Most servers support keys with a length of at least 4096 bits. Longer keys may not be accepted for DDOS protection purposes:

If you had previously created a different key, you will be asked if you wish to overwrite your previous key:

If you choose “yes”, your previous key will be overwritten and you will no longer be able to log in to servers using that key. Because of this, be sure to overwrite keys with caution.

Removing or Changing the Passphrase on a Private Key

If you have generated a passphrase for your private key and wish to change or remove it, you can do so easily.

Note: To change or remove the passphrase, you must know the original passphrase. If you have lost the passphrase to the key, there is no recourse and you will have to generate a new key pair.

To change or remove the passphrase, simply type:

Enter file in which the key is (/root/.ssh/id_rsa):

You can type the location of the key you wish to modify or press ENTER to accept the default value:

Enter old passphrase:

Enter the old passphrase that you wish to change. You will then be prompted for a new passphrase:

Enter new passphrase (empty for no passphrase):
Enter same passphrase again:

Here, enter your new passphrase or press ENTER to remove the passphrase.

Displaying the SSH Key Fingerprint

To find out the fingerprint of an SSH key, type:

You can press ENTER if that is the correct location of the key, else enter the revised location. You will be given a string which contains the bit-length of the key, the fingerprint, and account and host it was created for, and the algorithm used:

Copying your Public SSH Key to a Server with SSH-Copy-ID

To copy your public key to a server, allowing you to authenticate without a password, a number of approaches can be taken.

If you currently have password-based SSH access configured to your server, and you have the ssh-copy-id utility installed, this is a simple process. The ssh-copy-id tool is included in many Linux distributions’ OpenSSH packages, so it very likely may be installed by default.

If you have this option, you can easily transfer your public key by typing:

You can now log in to that account without a password:

Copying your Public SSH Key to a Server Without SSH-Copy-ID

If you do not have the ssh-copy-id utility available, but still have password-based SSH access to the remote server, you can copy the contents of your public key in a different way.

You can output the contents of the key and pipe it into the ssh command. On the remote side, you can ensure that the ~/.ssh directory exists, and then append the piped contents into the ~/.ssh/authorized_keys file:

You will be asked to supply the password for the remote account:

After entering the password, your key will be copied, allowing you to log in without a password:

Copying your Public SSH Key to a Server Manually

If you do not have password-based SSH access available, you will have to add your public key to the remote server manually.

On your local machine, you can find the contents of your public key file by typing:

You can copy this value, and manually paste it into the appropriate location on the remote server. You will have to log in to the remote server through other means (like the DigitalOcean web console).

On the remote server, create the ~/.ssh directory if it does not already exist:

Afterwards, you can create or append the ~/.ssh/authorized_keys file by typing:

public_key_string ~/.ssh/authorized_keys

You should now be able to log in to the remote server without a password.

Отключение аутентификации по паролю

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

Предупреждение: перед выполнением этих действий необходимо убедиться, что публичный ключ установлен на сервере. В противном случае вы заблокируете доступ к серверу!

Откройте файл конфигурации sshd, воспользовавшись пользователем root или пользователем с привилегиями sudo:

Найдите строку Password Authentication и раскомментируйте ее, удалив символ # в начале строки. Теперь вы можете указать значение no:

Вы должны также изменить значения двух других настроек (если вы не вносили изменения в этот файл ранее) — PubkeyAuthentication и ChallengeResponseAuthentication. Значения устанавливаются по умолчанию и выглядят следующим образом:

Читайте также:  Как можно опубликовать сайт

PubkeyAuthentication yes
ChallengeResponseAuthentication no

После внесения изменений сохраните и закройте файл.

Теперь нужно перезапустить демон SSH:

Теперь аутентификация по паролю должна быть отключена, а ваш сервер должен быть доступен только с помощью аутентификации по ключу SSH.

Как работает SSH

По протоколу SSH работает набор программ, служащих для выполнения различных действий на удаленной операционной системе. Например, программа sshd обеспечивает серверную функциональность SSH, она должна быть запущена на SSH-сервере. Программа ssh запускается на SSH-клиенте и позволяет устанавливать соединение с удаленным хостом, регистрироваться на нем, работать с удаленной машиной через SSH-соединение.

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

Этот материал был полезен?

Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы

Первая версия, которая получила название SSH-1, была создана в далеком 1995-м году, автором является Тату Уленен. Основной задачей этой версии, было обеспечение более высокого уровня конфиденциальности, в сравнении с протоколами rsh, telnet и rlogin, которые использовались в то время.

Главным преимуществом первой версии, перед своими конкурентами, была устойчивость к прослушиванию трафика (снифинг), однако данный протокол все еще был уязвим для атак, принцип которых базируется на том, что злоумышленник становится посредником между двумя сторонами обмена данными, и может ретранслировать их или изменять.

Именно поэтому в 1996-м, был разработан протокол SSH-2, который и используется в наше время. Данная версия предусматривает использование специальной авторизации при подключении к серверу, что не дает возможности третьим лицам подключиться к потоку данных.

На сегодняшний день под термином SSH, воспринимается исключительно вторая версия.

Client-Side Configuration Options

In the next section, we’ll focus on some adjustments that you can make on the client side of the connection.

Defining Server-Specific Connection Information

On your local computer, you can define individual configurations for some or all of the servers you connect to. These can be stored in the ~/.ssh/config file, which is read by your SSH client each time it is called.

Create or open this file in your text editor on your local computer:

An example configuration would be:

You can also use wildcards to match more than one host. Keep in mind that later matches can override earlier ones. Because of this, you should put your most general matches at the top. For instance, you could default all connections to not allow X forwarding, with an override for your_domain by having this in your file:

Save and close the file when you are finished.

Keeping Connections Alive to Avoid Timeout

If you find yourself being disconnected from SSH sessions before you are ready, it is possible that your connection is timing out.

You can configure your client to send a packet to the server every so often in order to avoid this situation:

On your local computer, you can configure this for every connection by editing your ~/.ssh/config file. Open it now:

If one does not already exist, at the top of the file, define a section that will match all hosts. Set the ServerAliveInterval to “120” to send a packet to the server every two minutes. This should be enough to notify the server not to close the connection:

Disabling Host Checking

By default, whenever you connect to a new server, you will be shown the remote SSH daemon’s host key fingerprint.

The authenticity of host ‘111.111.11.111 (111.111.11.111)’ can’t be established.
ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe.
Are you sure you want to continue connecting (yes/no)? yes

In certain circumstances, you may wish to disable this feature. Note: This can be a big security risk, so make sure you know what you are doing if you set your system up like this.

To make the change, the open the ~/.ssh/config file on your local computer:

You can enable the checking on a case-by-case basis by reversing those options for other hosts. The default for StrictHostKeyChecking is ask:

Multiplexing SSH Over a Single TCP Connection

There are situations where establishing a new TCP connection can take longer than you would like. If you are making multiple connections to the same machine, you can take advantage of multiplexing.

SSH multiplexing re-uses the same TCP connection for multiple SSH sessions. This removes some of the work necessary to establish a new session, possibly speeding things up. Limiting the number of connections may also be helpful for other reasons.

To set up multiplexing, you can manually set up the connections, or you can configure your client to automatically use multiplexing when available. We will demonstrate the second option here.

To configure multiplexing, edit your SSH client’s configuration file on your local machine:

If you do not already have a wildcard host definition at the top of the file, add one now (as Host *). We will be setting the ControlMaster, ControlPath, and ControlPersist values to establish our multiplexing configuration.

Setting the ControlPersist option to 1 will allow the initial master connection to be backgrounded. The 1 specifies that the TCP connection should automatically terminate one second after the last SSH session is closed:

Save and close the file when you are finished. Now, we need to actually create the directory we specified in the control path:

Now, any sessions that are established with the same machine will attempt to use the existing socket and TCP connection. When the last session exists, the connection will be torn down after one second.

If for some reason you need to bypass the multiplexing configuration temporarily, you can do so by passing the -S flag with none:

Для чего используются SSH и SFTP протоколы

Чаще всего протоколы SSH и SFTP используются для удаленной работы с операционной системой или переноса большого количества файлов.

Например, клиент берет в аренду сервер или какую-то часть серверного пространства. Возникает необходимость переносить туда уже имеющиеся данные клиента, например, сайт или почтовые файлы. Провайдер должен обеспечить надежность и быстроту обмена данными с его сервером, особенно если речь идет о больших объемах информации и ее высокой конфиденциальности. В этом случае на удаленной машине (в данном случае — виртуальном сервере) устанавливается SSH-сервер (со встроенным SFTP-протоколом), а на клиентском компьютере — SSH-клиент. Создается SSH-туннель, и обмен данными между клиентом и удаленным сервером осуществляется через надежное соединение со всеми преимуществами протокола, описанными выше.

Также SSH может использоваться для удаленной работы по защищенному соединению с различными сервисами провайдера, такими как программное обеспечение, операционные системы и т.д.

Советы по настройке протокола SSH и дальнейшему применению

Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы

В ситуации, при которой вы работаете через SSH, и хотите существенно повысить безопасность соединения, рекомендуем выполнить следующие действия:

  • Запретить отключение входа по паролю или подключения с пустым паролем;
  • Запретить удаленный root-доступ;
  • Ограничить список IP, для которых, будет разрешен доступ;

Также стоит регулярно просматривать сообщения об ошибках аутентификации. Это позволит выявить с каких IP регулярно пытаются ломать ваш сервер, и соответственно запретить для них доступ к SSH.

Еще одним важным моментом, который позволит существенно увеличить безопасность соединения, является использование длинных ключей для SSH2. Считается, что длинный ключ содержит более 2048 бит. Вообще, надежной, система шифрования считается если длинна ключа равна 1024 бит, или более.

Дополнительно, улучшить защиту вашего соединения, поможет использование ловушек, которые имитируют SSH-сервис, технология Port knocking, система обнаружения вторжений в канал (IDS).

Настройка SSH

При изменении конфигурации SSH вы меняете настройки сервера sshd.

В Ubuntu основной файл конфигурации sshd находится в каталоге /etc/ssh/sshd_config.

Выполните резервное копирование текущей версии этого файла перед началом редактирования:

Откройте файл в текстовом редакторе:

Скорее всего, вы захотите оставить большинство опций в этом файле без изменений. Однако существует несколько настроек, на которые вам стоит обратить особое внимание:

Объявление порта указывает, подключения к какому порту будет отслеживать сервер sshd. По умолчанию используется порт 22. Вам, скорее всего, не придется изменять данную настройку, если только у вас нет конкретных причин для иного решения. Если вы решите изменить порт, позже мы покажем, как подключиться к новому порту.

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key

В объявлениях ключей хоста указывается, где нужно искать глобальные ключи хоста. Мы обсудим, что такое ключ хоста, позже.

SyslogFacility AUTH
LogLevel INFO

Эти две строки указывают на уровень логирования, который необходимо использовать.

Если вы сталкиваетесь с проблемами при работе с SSH, увеличение объема логируемых данных может быть хорошим решением, которое поможет понять, в чем заключается проблема.

LoginGraceTime 120
PermitRootLogin yes
StrictModes yes

Эти параметры определяют некоторые данные для входа в систему.

Опция LoginGraceTime определяет количество секунд, в течение которых следует сохранять подключение при отсутствии успешных попыток входа в систему.

Возможно, вам может быть полезным задать для этого параметра чуть большее количество времени, чем то, которое вам обычно требуется для входа.

PermitRootLogin определяет, разрешен ли вход с помощью пользователя с правами root.

В большинстве случаев необходимо изменить значение на no, если вы создали учетную запись пользователя, которая имеет доступ к высокому уровню привилегий (через su или sudo) и может использоваться для входа в систему через ssh.

strictModes — это защитник, который будет препятствовать попыткам входа, если файлы аутентификации доступны для чтения всем.

Он позволяет предотвратить попытки входа в систему, когда файлы конфигурации не находятся в безопасном состоянии.

X11Forwarding yes
X11DisplayOffset 10

Эти параметры используются для настройки такой возможности, как X11 Forwarding. X11 Forwarding позволяет просматривать графический пользовательский интерфейс (GUI) удаленной системы на локальной системе.

Эта функция должна быть активирована на сервере и передана клиенту SSH во время подключения с помощью опции -X.

После внесения изменений сохраните и закройте файл, введя CTRL+X, Y, а затем нажмите ENTER.

Если вы внесли изменения в какие-либо настройки в файле /etc/ssh/sshd_config, необходимо перезапустить ваш сервер sshd, чтобы изменения вступили в силу:

Вы должны тщательно протестировать ваши изменения, чтобы убедиться, что все работает так, как вы ожидаете.

Вы можете использовать несколько активных сеансов во время внесения изменений. Это позволит вам вернуться к первоначальной конфигурации, если это потребуется.

Опции для клиентской стороны

Существует ряд опциональных флагов, которые вы можете использовать при подключении через SSH.

Некоторые из них могут быть необходимы при наличии определенных настроек конфигурации sshd на удаленном хосте.

Например, если вы изменили номер порта в конфигурации sshd, вам потребуется указать этот порт на клиентской стороне с помощью следующей команды:

Если вы хотите выполнить отдельную команду на удаленной системе, вы можете указать ее после имени хоста следующим образом:

В результате будет установлено подключение к удаленному компьютеру, а после успешной аутентификации команда будет выполнена.

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

При наличии соответствующих инструментов на вашем компьютере программы GUI, которые вы используете на удаленной системе, теперь будут открываться в отдельном окне на локальной системе.

Базовый синтаксис

Чтобы подключиться к удаленной системе с помощью SSH, мы будем использовать команду ssh. В самом базовом виде команда имеет следующую форму:

Эта команда предполагает, что ваше имя пользователя на удаленной системе совпадает с именем пользователя в локальной системе.

Если ваше локальное имя пользователя отличается от имени пользователя в удаленной системе, вы можете задать его, используя следующий синтаксис:

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

Чтобы завершить сеанс ssh и вернуться в сеанс локальной оболочки, введите следующую команду:

Читайте также:  Что значит автоплатеж

Using SSH Escape Codes to Control Connections

Even after establishing an SSH session, it is possible to exercise control over the connection from within the terminal. We can do this with something called SSH escape codes, which allow us to interact with our local SSH software from within a session.

Forcing a Disconnect from the Client-Side (How to Exit Out of a Stuck or Frozen Session)

One of the most useful feature of OpenSSH that goes largely unnoticed is the ability to control certain aspects of the session from within.

These commands can be executed starting with the ~ control character within an SSH session. Control commands will only be interpreted if they are the first thing that is typed after a newline, so always press ENTER one or two times prior to using one.

One of the most useful controls is the ability to initiate a disconnect from the client. SSH connections are typically closed by the server, but this can be a problem if the server is suffering from issues or if the connection has been broken. By using a client-side disconnect, the connection can be cleanly closed from the client.

To close a connection from the client, use the control character (~), with a dot. If your connection is having problems, you will likely be in what appears to be a stuck terminal session. Type the commands despite the lack of feedback to perform a client-side disconnect:

The connection should immediately close, returning you to your local shell session.

Placing an SSH Session into the Background

One of the most useful feature of OpenSSH that goes largely unnoticed is the ability to control certain aspects of the session from within the connection.

These commands can be executed starting with the ~ control character from within an SSH connection. Control commands will only be interpreted if they are the first thing that is typed after a newline, so always press ENTER one or two times prior to using one.

One capability that this provides is to put an SSH session into the background. To do this, we need to supply the control character (~) and then execute the conventional keyboard shortcut to background a task (CTRL-z):

This will place the connection into the background, returning you to your local shell session. To return to your SSH session, you can use the conventional job control mechanisms.

You can immediately re-activate your most recent backgrounded task by typing:

If you have multiple backgrounded tasks, you can see the available jobs by typing:

You can then bring any of the tasks to the foreground by using the index in the first column with a percentage sign:

Changing Port Forwarding Options on an Existing SSH Connection

These capabilities are part of the SSH command line interface, which can be accessed during a session by using the control character (~) and “C”:

You will be given an SSH command prompt, which has a very limited set of valid commands. To see the available options, you can type -h from this prompt. If nothing is returned, you may have to increase the verbosity of your SSH output by using ~v a few times:

So, to set up a local port forward, you may type:

Port 8888 on your local computer will now be able to communicate with the web server on the host you are connecting to. When you are finished, you can tear down that forward by typing:

Setting Up SSH Tunnels

Tunneling other traffic through a secure SSH tunnel is an excellent way to work around restrictive firewall settings. It is also a great way to encrypt otherwise unencrypted network traffic.

Configuring Local Tunneling to a Server

SSH connections can be used to tunnel traffic from ports on the local host to ports on a remote host.

This is often used to tunnel to a less restricted networking environment by bypassing a firewall. Another common use is to access a “localhost-only” web interface from a remote location.

To establish a local tunnel to your remote server, you need to use the -L parameter when connecting and you must supply three pieces of additional information:

  • The local port where you wish to access the tunneled connection.
  • The host that you want your remote host to connect to.
  • The port that you want your remote host to connect on.

These are given, in the order above (separated by colons), as arguments to the -L flag. We will also use the -f flag, which causes SSH to go into the background before executing and the -N flag, which does not open a shell or execute a program on the remote side.

For instance, to connect to your_domain on port 80 on your remote host, making the connection available on your local machine on port 8888, you could type:

Now, if you point your local web browser to 127.0.0.1:8888, you should see whatever content is at your_domain on port 80.

A more general guide to the syntax is:

Since the connection is in the background, you will have to find its PID to kill it. You can do so by searching for the port you forwarded:

You can then kill the process by targeting the PID, which is the number in the second column of the line that matches your SSH command:

Another option is to start the connection without the -f flag. This will keep the connection in the foreground, preventing you from using the terminal window for the duration of the forwarding. The benefit of this is that you can easily kill the tunnel by typing CTRL-C.

Configuring Remote Tunneling to a Server

In a remote tunnel, a connection is made to a remote host. During the creation of the tunnel, a remote port is specified. This port, on the remote host, will then be tunneled to a host and port combination that is connected to from the local computer. This will allow the remote computer to access a host through your local computer.

This can be useful if you need to allow access to an internal network that is locked down to external connections. If the firewall allows connections out of the network, this will allow you to connect out to a remote machine and tunnel traffic from that machine to a location on the internal network.

To establish a remote tunnel to your remote server, you need to use the -R parameter when connecting and you must supply three pieces of additional information:

  • The port where the remote host can access the tunneled connection.
  • The host that you want your local computer to connect to.
  • The port that you want your local computer to connect to.

These are given, in the order above (separated by colons), as arguments to the -R flag. We will also use the -f flag, which causes SSH to go into the background before executing and the -N flag, which does not open a shell or execute a program on the remote side.

For instance, to connect to your_domain on port 80 on our local computer, making the connection available on our remote host on port 8888, you could type:

Now, on the remote host, opening a web browser to 127.0.0.1:8888 would allow you to see whatever content is at your_domain on port 80.

You can then kill the process by targeting the PID, which is the number in the second column, of the line that matches your SSH command:

Configuring Dynamic Tunneling to a Remote Server

A dynamic tunnel is similar to a local tunnel in that it allows the local computer to connect to other resources through a remote host. A dynamic tunnel does this by simply specifying a single local port. Applications that wish to take advantage of this port for tunneling must be able to communicate using the SOCKS protocol so that the packets can be correctly redirected at the other side of the tunnel.

Traffic that is passed to this local port will be sent to the remote host. From there, the SOCKS protocol will be interpreted to establish a connection to the desired end location. This set up allows a SOCKS-capable application to connect to any number of locations through the remote server, without multiple static tunnels.

To establish the connection, we will pass the -D flag along with the local port where we wish to access the tunnel. We will also use the -f flag, which causes SSH to go into the background before executing and the -N flag, which does not open a shell or execute a program on the remote side.

For instance, to establish a tunnel on port 7777, you can type:

From here, you can start pointing your SOCKS-aware application (like a web browser), to the port you selected. The application will send its information into a socket associated with the port.

Где найти доступы к серверу

Как подключиться по SSH с компьютера на ОС

Если на вашем компьютере установлена ОС Windows, а на сервере — UNIX-подобная система (например, Ubuntu, Debian, CentOS и др.), то для установки SSH-соединения можно использовать PuTTY. Это бесплатная программа под Windows состоит из одного запускаемого файла и не требует установки.

Чтобы установить соединение при помощи PuTTY, необходимо проделать следующие действия:

По умолчанию никаких настроек программы менять не нужно. Достаточно убедиться, что указан порт Port 22 и тип соединения Connection type — SSH.

Может появиться предупреждение системы безопасности PuTTY — оно срабатывает при подключении к новому серверу.  Нажмите Да — и соединение продолжится.

4. В следующей строке введите пароль пользователя. При вводе пароля символы в командной строке не отображаются: можно набрать пароль вслепую или вставить кликом правой кнопки мыши, предварительно скопировав (Ctrl+C) его из письма с доступами. После ввода нажмите клавишу Enter. Если имя пользователя или пароль указаны неправильно, выведется ошибка «Access denied». В случае успешного подключения откроется командная строка виртуального сервера.

Как использовать протокол SSH?

Что бы это сделать, нам понадобятся соответствующие клиент и сервер. На сегодня, существует большое количество оболочек, клиентов и серверов для разных ОС.

Какие есть SSH серверы?

Для системы распространения ПО BSD, используется стандартный OpenSSH. Также есть множество различных решений для серверов на Linux или Windows.

Клиенты и оболочки для SSH

На сегодняшний день, есть множество оболочек и клиентов SSH-протокола, для следующих систем:

  • GNULinux;
  • Windows, NT, Mobile;
  • BSD;
  • Mac OS;
  • J2ME;
  • Java;
  • iPhone;
  • Android;
  • MeeGo 1.2 Harmattan;
  • Symbian OS;
  • Blackberry.

Одним из самых распространенных SSH-клиентов, который в частности рекомендуют многие специалисты, является FileZilla.

Server-Side Configuration Options

This section contains some common server-side configuration options that can shape the way that your server responds and what types of connections are allowed.

Disabling Password Authentication

To do this, connect to your remote server and open the /etc/ssh/sshd_config file with root or sudo privileges:

Inside of the file, search for the PasswordAuthentication directive. If it is commented out, uncomment it. Set it to no to disable password logins:

After you have made the change, save and close the file. To implement the changes, you should restart the SSH service.

Now, all accounts on the system will be unable to log in with SSH using passwords.

Changing the Port that the SSH Daemon Runs On

Once you are inside, you can change the port that SSH runs on by finding the Port 22 specification and modifying it to reflect the port you wish to use. For instance, to change the port to 4444, put this in your file:

Читайте также:  Понимание ошибки статуса 403: распространенные причины и решения

#Port 22
Port 4444

Save and close the file when you are finished. To implement the changes, you must restart the SSH daemon.

After the daemon restarts, you will need to authenticate by specifying the port number (demonstrated in an earlier section).

Limiting the Users Who can Connect Through SSH

On your remote server, open this file now with root or sudo privileges:

Save and close the file. Restart the daemon to implement your changes.

If you are more comfortable with group management, you can use the AllowGroups directive instead. If this is the case, just add a single group that should be allowed SSH access (we will create this group and add members momentarily):

Now, you can create a system group (without a home directory) matching the group you specified by typing:

Now, restart the SSH daemon to implement your changes.

Disabling Root Login

To do this, open the SSH daemon configuration file with root or sudo on your remote server.

Inside, search for a directive called PermitRootLogin. If it is commented, uncomment it. Change the value to “no”:

Save and close the file. To implement your changes, restart the SSH daemon.

There are some cases where you might want to disable root access generally, but enable it in order to allow certain applications to run correctly. An example of this might be a backup routine.

Now, log into the remote server. We will need to adjust the entry in the authorized_keys file, so open it with root or sudo access:

At the beginning of the line with the key you uploaded, add a command= listing that defines the command that this key is valid for. This should include the full path to the executable, plus any arguments:

Now, open the sshd_config file with root or sudo privileges:

Find the directive PermitRootLogin, and change the value to forced-commands-only. This will only allow SSH key logins to use root when a command has been specified for the key:

Save and close the file. Restart the SSH daemon to implement your changes.

Forwarding X Application Displays to the Client

The SSH daemon can be configured to automatically forward the display of X applications on the server to the client machine. For this to function correctly, the client must have an X windows system configured and enabled.

To enable this functionality, log in to your remote server and edit the sshd_config file as root or with sudo privileges:

Search for the X11Forwarding directive. If it is commented out, uncomment it. Create it if necessary and set the value to “yes”:

Save and close the file. Restart your SSH daemon to implement these changes.

To connect to the server and forward an application’s display, you have to pass the -X option from the client upon connection:

Graphical applications started on the server through this session should be displayed on the local computer. The performance might be a bit slow, but it is very helpful in a pinch.

Как подключиться к серверу по SSH с компьютера на Linux/MacOS

Подключиться по SSH к виртуальному серверу можно через терминал — в обоих случаях это приложение предустановлено.

В операционных системах семейства Linux (Ubuntu и др.) его можно открыть сочетанием клавиш .

В MacOS приложение Терминал можно найти через Spotlight (иконка поиска в правом верхнем углу экрана).

Подключиться к виртуальному серверу по SSH можно одной командой:

где 22 — порт, по которому будет произведено подключение по SSH.

После ввода команды система запросит подтверждение подключения (необходимо ввести yes и нажать Enter) и пароль пользователя. После ввода нажмите клавишу Enter — откроется SSH-соединение:

  • Read the SSH Overview section first if you are unfamiliar with SSH in general or are just getting started.
  • Use the Contents menu on the left side of this page (at wide page widths) or your browser’s find function to locate the sections you need.
  • Copy and paste the command-line examples given, substituting the highlighted values with your own values.

Выполнение входа через SSH с использованием ключей

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

Как работает аутентификация с помощью ключей?

Аутентификация с помощью ключей реализуется путем создания пары ключей: приватного ключа и публичного ключа.

Приватный ключ располагается на клиентском компьютере, этот ключ защищен и хранится в секрете.

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

При попытке подключения с использованием пары ключей сервер будет использовать публичный ключ для создания сообщения для клиентского компьютера, которое может быть прочитано только с помощью приватного ключа.

Затем клиентский компьютер отправляет соответствующий ответ обратно серверу, после чего сервер будет знать, что клиент не является поддельным.

Весь этот процесс выполняется в автоматическом режиме после того, как вы настроите ключи.

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

Введите следующую команду в командной строке:

ssh-keygen rsa

Нажмите ENTER, чтобы принять используемые по умолчанию значения. Ваши ключи будут сгенерированы в файлах ~/.ssh/id_rsa.pub и ~/.ssh/id_rsa.

Перейдите в каталог .ssh с помощью следующей команды:

Просмотрите данные о разрешениях для файлов:

-rw-r—r— 1 demo demo 807 Sep 9 22:15 authorized_keys
-rw——- 1 demo demo 1679 Sep 9 23:13 id_rsa
-rw-r—r— 1 demo demo 396 Sep 9 23:13 id_rsa.pub

Как вы можете видеть, файл id_rsa доступен для чтения и записи только владельцу. Именно такие разрешения позволяют сохранить его в секрете.

В то же время файл id_rsa.pub может использоваться совместно и имеет соответствующие разрешения для данной деятельности.

Как передать ваш публичный ключ на сервер

Если в настоящее время вы используете доступ к серверу с помощью пароля, вы можете скопировать ваш публичный ключ на сервер, воспользовавшись данной командой:

В результате будет создан сеанс SSH. Когда вы введете пароль, ваш публичный ключ будет скопирован в файл авторизованных ключей сервера, что позволит не использовать пароль при входе в следующий раз.

Как работает SSH?

SSH выполняет подключение клиентской программы к серверу ssh с именем sshd.

В предыдущем разделе команда ssh использовалась для вызова клиентской программы. Сервер ssh уже запущен на удаленном хосте remote_host, который мы указали.

На вашем сервере должен быть запущен сервер sshd. Если это не так, вам может потребоваться подключение к серверу через веб-консоль или локальную последовательную консоль.

Процесс запуска сервера ssh зависит от дистрибутива Linux, который вы используете.

В Ubuntu вы можете запустить сервер ssh с помощью следующей команды:

Эта команда должна запускать сервер sshd, после чего вы сможете выполнять удаленный вход.

Basic Connection Instructions

To connect to a remote server and open a shell session there, you can use the ssh command.

Your first time connecting to a new host, you will see a message that looks like this:

Type yes to accept the authenticity of the remote host.

If you are using password authentication, you will be prompted for the password for the remote account here. If you are using SSH keys, you will be prompted for your private key’s passphrase if one is set, otherwise you will be logged in automatically.

Running a Single Command on a Remote Server

To run a single command on a remote server instead of spawning a shell session, you can add the command after the connection information, like this:

This will connect to the remote host, authenticate with your credentials, and execute the command you specified. The connection will immediately close afterwards.

Logging in to a Server with a Different Port

By default the SSH daemon on a server runs on port 22. Your SSH client will assume that this is the case when trying to connect. If your SSH server is listening on a non-standard port (this is demonstrated in a later section), you will have to specify the new port number when connecting with your client.

You can do this by specifying the port number with the -p option:

To avoid having to do this every time you log in to your remote server, you can create or edit a configuration file in the ~/.ssh directory within the home directory of your local computer.

Edit or create the file now by typing:

In here, you can set host-specific configuration options. To specify your new port, use a format like this:

Host remote_alias
HostName remote_host
Port port_num

This will allow you to log in without specifying the specific port number on the command line.

Adding your SSH Keys to an SSH Agent to Avoid Typing the Passphrase

If you have a passphrase on your private SSH key, you will be prompted to enter the passphrase every time you use it to connect to a remote host.

To avoid having to repeatedly do this, you can run an SSH agent. This small utility stores your private key after you have entered the passphrase for the first time. It will be available for the duration of your terminal session, allowing you to connect in the future without re-entering the passphrase.

This is also important if you need to forward your SSH credentials (shown later).

This will start the agent program and place it into the background. Now, you need to add your private key to the agent, so that it can manage your key:

Enter passphrase for /home/demo/.ssh/id_rsa:
Identity added: /home/demo/.ssh/id_rsa (/home/demo/.ssh/id_rsa)

You will have to enter your passphrase (if one is set). Afterwards, your identity file is added to the agent, allowing you to use your key to sign in without having to re-enter the passphrase again.

Forwarding your SSH Credentials to Use on a Server

If you wish to be able to connect without a password to one server from within another server, you will need to forward your SSH key information. This will allow you to authenticate to another server through the server you are connected to, using the credentials on your local computer.

To start, you must have your SSH agent started and your SSH key added to the agent (see earlier). After this is done, you need to connect to your first server using the -A option. This forwards your credentials to the server for this session:

From here, you can SSH in to any other host that your SSH key is authorized to access. You will connect as if your private SSH key were located on this server.

Выводы

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

Наиболее распространенным вариантом, сегодня является OpenSSH, благодаря возможности бесплатного использования и открытому коду, что позволяет оптимизировать все под свои нужды.

На сегодняшний день, использование сетевого протокола SSH, отлично поддерживается многими ОС, как для клиента, так и для сервера.

Очень важным моментом можно назвать то, что клиент и сервер для протокола SSH, требуют специальной настройки, которая далеко не всегда по силам человеку, не обладающему определенными знаниями. Именно поэтому многие хостинги предлагают своим клиентам услуги по созданию и настройке защищенного соединения.

Протокол SSH (Secure Shell) — что это такое, какие нужны настройки для работы

SEO-эксперт, вебмастер с 2009 года, CEO компании CyberShark. За время работы в сфере создания и продвижения сайтов протестировал более сотни хостингов.

Заключение

Обучение работе с SSH точно будет полезным, хотя бы потому, что это очень распространенный инструмент.

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

Оцените статью
Хостинги