- Ubuntu Documentation
- Introduction
- Disable Password Authentication
- Disable Forwarding
- Specify Which Accounts Can Use SSH
- Rate-limit the connections
- Log More Information
- Display a Banner
- Troubleshooting
- Полное руководство по настройке SSH в Ubuntu
- Основы SSH
- Настройка SSH-сервера в Ubuntu
- Шаг 1. Установите необходимые пакеты
- Шаг 2: Проверка статуса сервера
- Шаг 3. Разрешение SSH через брандмауэр
- Подключение к удаленной системе с вашего локального компьютера
- Закрытие SSH-соединения
- Остановка и отключение SSH в Ubuntu
- Другие клиенты SSH
- Заключение
Ubuntu Documentation
Introduction
Once you have installed an OpenSSH server,
you will need to configure it by editing the sshd_config file in the /etc/ssh directory.
sshd_config is the configuration file for the OpenSSH server. ssh_config is the configuration file for the OpenSSH client. Make sure not to get them mixed up.
First, make a backup of your sshd_config file by copying it to your home directory, or by making a read-only copy in /etc/ssh by doing:
Creating a read-only backup in /etc/ssh means you’ll always be able to find a known-good configuration when you need it.
Once you’ve backed up your sshd_config file, you can make changes with any text editor, for example;
runs the standard text editor in Ubuntu 12.04 or more recent. For older versions replace «sudo» with «gksudo». Once you’ve made your changes (see the suggestions in the rest of this page), you can apply them by saving the file then doing:
If you get the error, «Unable to connect to Upstart», restart ssh with the following:
Configuring OpenSSH means striking a balance between security and ease-of-use. Ubuntu’s default configuration tries to be as secure as possible without making it impossible to use in common use cases. This page discusses some changes you can make, and how they affect the balance between security and ease-of-use. When reading each section, you should decide what balance is right for your specific situation.
Disable Password Authentication
Because a lot of people with SSH servers use weak passwords, many online attackers will look for an SSH server, then start guessing passwords at random. An attacker can try thousands of passwords in an hour, and guess even the strongest password given enough time. The recommended solution is to use SSH keys instead of passwords. To be as hard to guess as a normal SSH key, a password would have to contain 634 random letters and numbers. If you’ll always be able to log in to your computer with an SSH key, you should disable password authentication altogether.
If you disable password authentication, it will only be possible to connect from computers you have specifically approved. This massively improves your security, but makes it impossible for you to connect to your own computer from a friend’s PC without pre-approving the PC, or from your own laptop when you accidentally delete your key.
It’s recommended to disable password authentication unless you have a specific reason not to.
To disable password authentication, look for the following line in your sshd_config file:
#PasswordAuthentication yes
replace it with a line that looks like this:
PasswordAuthentication no
Once you have saved the file and restarted your SSH server, you shouldn’t even be asked for a password when you log in.
Disable Forwarding
By default, you can tunnel network connections through an SSH session. For example, you could connect over the Internet to your PC, tunnel a remote desktop connection, and access your desktop. This is known as «port forwarding».
By default, you can also tunnel specific graphical applications through an SSH session. For example, you could connect over the Internet to your PC and run nautilus «file://$HOME» to see your PC’s home folder. This is known as «X11 forwarding».
While both of these are very useful, they also give more options to an attacker who has already guessed your password. Disabling these options gives you a little security, but not as much as you’d think. With access to a normal shell, a resourceful attacker can replicate both of these techniques and a specially-modified SSH client.
It’s only recommended to disable forwarding if you also use SSH keys with specified commands.
To disable forwarding, look for the following lines in your sshd_config:
AllowTcpForwarding yes
X11Forwarding yes
and replace them with:
AllowTcpForwarding no
X11Forwarding no
If either of the above lines don’t exist, just add the replacement to the bottom of the file. You can disable each of these independently if you prefer.
Specify Which Accounts Can Use SSH
You can explicitly allow or deny access for certain users or groups. For example, if you have a family PC where most people have weak passwords, you might want to allow SSH access just for yourself.
Allowing or denying SSH access for specific users can significantly improve your security if users with poor security practices don’t need SSH access.
It’s recommended to specify which accounts can use SSH if only a few users want (not) to use SSH.
To allow only the users Fred and Wilma to connect to your computer, add the following line to the bottom of the sshd_config file:
AllowUsers Fred Wilma
To allow everyone except the users Dino and Pebbles to connect to your computer, add the following line to the bottom of the sshd_config file:
DenyUsers Dino Pebbles
It’s possible to create very complex rules about who can use SSH — you can allow or deny specific groups of users, or users whose names match a specific pattern, or who are logging in from a specific location. For more details about how to create complex rules, see the sshd_config man page
Rate-limit the connections
It’s possible to limit the rate at which one IP address can establish new SSH connections by configuring the uncomplicated firewall (ufw). If an IP address is tries to connect more than 10 times in 30 seconds, all the following attempts will fail since the connections will be DROPped. The rule is added to the firewall by running a single command:
On a single-user or low-powered system, such as a laptop, the number of total simultaneous pending (not yet authorized) login connections to the system can also be limited. This example will allow two pending connections. Between the third and tenth connection the system will start randomly dropping connections from 30% up to 100% at the tenth simultaneous connection. This should be set in sshd_config.
MaxStartups 2:30:10
In a multi-user or server environment, these numbers should be set significantly higher depending on resources and demand to alleviate denial-of-access attacks. Setting a lower the login grace time (time to keep pending connections alive while waiting for authorization) can be a good idea as it frees up pending connections quicker but at the expense of convenience.
LoginGraceTime 30
Log More Information
By default, the OpenSSH server logs to the AUTH facility of syslog, at the INFO level. If you want to record more information — such as failed login attempts — you should increase the logging level to VERBOSE.
It’s recommended to log more information if you’re curious about malicious SSH traffic.
To increase the level, find the following line in your sshd_config:
LogLevel INFO
and change it to this:
LogLevel VERBOSE
Now all the details of ssh login attempts will be saved in your /var/log/auth.log file.
If you have started using a different port, or if you think your server is well-enough hidden not to need much security, you should increase your logging level and examine your auth.log file every so often. If you find a significant number of spurious login attempts, then your computer is under attack and you need more security.
Whatever security precautions you’ve taken, you might want to set the logging level to VERBOSE for a week, and see how much spurious traffic you get. It can be a sobering experience to see just how much your computer gets attacked.
Display a Banner
If you want to try to scare novice attackers, it can be funny to display a banner containing legalese. This doesn’t add any security, because anyone that’s managed to break in won’t care about a «no trespassing» sign—but it might give a bad guy a chuckle.
To add a banner that will be displayed before authentication, find this line:
#Banner /etc/issue.net
and replace it with:
Banner /etc/issue.net
This will display the contents of the /etc/issue.net file, which you should edit to your taste. If you want to display the same banner to SSH users as to users logging in on a local console, replace the line with:
Banner /etc/issue
To edit the banner itself try
Here is an example for what you might put in an issue or issue.net file and you could just copy&paste this in:
Troubleshooting
Once you have finished editing sshd_config, make sure to save your changes before restarting your SSH daemon.
First, check that your SSH daemon is running:
This command should produce a line like this:
If there is no line, your SSH daemon is not running. If it is, you should next check that it’s listening for incoming connections:
This command should produce a line that looks like one of these:
If there is more than one line, in particular with a port number different than 22, then your SSH daemon is listening on more than one port — you might want to go back and delete some Port lines in your sshd_config. If there are no lines, your SSH daemon is not listening on any ports, so you need to add at least one Port line. If the line specifies something other than «*:22» ([::]:22 is IPv6), then your SSH daemon is listening on a non-standard port or address, which you might want to fix.
Next, try logging in from your own computer:
This will print a lot of debugging information, and will try to connect to your SSH server. You should be prompted to type your password, and you should get another command-line when you type your password in. If this works, then your SSH server is listening on the standard SSH port. If you have set your computer to listen on a non-standard port, then you will need to go back and comment out (or delete) a line in your configuration that reads Port 22. Otherwise, your SSH server has been configured correctly.
To leave the SSH command-line, type:
If you have a local network (such as a home or office network), next try logging in from one of the other computers on your network. If nothing happens, you might need to tell your computer’s firewall to allow connections on port 22 (or from the non-standard port you chose earlier).
Finally, try logging in from another computer elsewhere on the Internet — perhaps from work (if your computer is at home) or from home (if your computer is at your work). If you can’t access your computer this way, you might need to tell your router’s firewall to allow connections from port 22, and might also need to configure Network Address Translation.
SSH/OpenSSH/Configuring (последним исправлял пользователь peterson-ca 2015-08-24 19:51:36)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Полное руководство по настройке SSH в Ubuntu
В наши дни SSH стал методом по умолчанию для доступа к удаленному серверу Linux.
SSH расшифровывается как Secure Shell и представляет собой мощный, эффективный и популярный сетевой протокол, используемый для удаленной связи между двумя компьютерами. И давайте не будем забывать о защищенной части его имени; SSH шифрует весь трафик для предотвращения таких атак, как угон и подслушивание, предлагая различные методы аутентификации и множество вариантов конфигурации.
В этом руководстве для начинающих вы узнаете:
- Основная концепция SSH
- Настройка SSH-сервера (в системе, к которой вы хотите получить удаленный доступ)
- Подключение к удаленному серверу через SSH с клиентской машины (вашего персонального компьютера)
Основы SSH
Прежде чем вы увидите какой-либо процесс настройки, будет лучше пройти через базовую концепцию SSH.
Протокол SSH основан на архитектуре сервер-клиент. «Сервер» позволяет «клиенту» подключаться по каналу связи. Этот канал зашифрован, и обмен регулируется использованием открытых и закрытых ключей SSH.
С сайта https://www.ssh.com/academy/ssh
OpenSSH — один из самых популярных инструментов с открытым исходным кодом, который обеспечивает функциональность SSH в Linux, BSD и Windows.
Для успешной настройки SSH вам необходимо:
- Установите компоненты сервера SSH на машине, которая действует как сервер. Это обеспечивается пакетом openssh-server.
- Установите клиентский компонент SSH на машину, с которой вы хотите подключиться к удаленному серверу. Это обеспечивается пакетом openssh-client, и с ним предустановлено большинство дистрибутивов Linux и BSD.
Важно различать сервер и клиент. Возможно, вы не захотите, чтобы ваш персональный компьютер работал как SSH-сервер, если у вас нет веских причин, по которым вы хотите, чтобы другие подключались к вашей системе через SSH.
Как правило, у вас есть выделенная система, работающая в качестве сервера. Например, Raspberry Pi с сервером Ubuntu. Вы включаете SSH на Raspberry Pi, чтобы вы могли контролировать и управлять устройством со своего основного персонального компьютера, используя SSH в терминале.
Обладая этой информацией, давайте посмотрим, как настроить SSH-сервер в Ubuntu.
Настройка SSH-сервера в Ubuntu
Настроить SSH не сложно, для этого нужно всего несколько шагов:
- Пользователь с привилегиями sudo на серверной машине
- Подключение к Интернету для загрузки необходимых пакетов.
Опять же, установка SSH-сервера должна выполняться в системе, которую вы хотите использовать как сервер и к которой вы хотите подключиться удаленно через SSH.
Шаг 1. Установите необходимые пакеты
Начнем с открытия окна терминала и ввода необходимых команд.
Не забудьте обновить свою систему Ubuntu перед установкой новых пакетов или программного обеспечения, чтобы убедиться, что вы используете последние версии.
Пакет, необходимый для запуска SSH-сервера, предоставляется компонентом openssh-server из OpenSSH:
Шаг 2: Проверка статуса сервера
После завершения загрузки и установки пакета служба SSH должна быть уже запущена, но для уверенности мы проверим ее с помощью:
Вы также можете использовать команды systemd:
Вы должны увидеть что-то подобное с выделенным словом Active. Нажмите q, чтобы вернуться в командную строку.
Если в вашем случае сервис не работает, вам нужно будет активировать его следующим образом:
Шаг 3. Разрешение SSH через брандмауэр
Ubuntu поставляется с утилитой межсетевого экрана под названием UFW (UncomplicatedFirewall), которая представляет собой интерфейс для iptables, который, в свою очередь, управляет сетевыми правилами. Если брандмауэр активен, он может помешать подключению к вашему SSH-серверу.
Чтобы настроить UFW так, чтобы он разрешал требуемый доступ, вам необходимо выполнить следующую команду:
Статус UFW можно проверить, запустив sudo ufw status.
На данном этапе наш SSH-сервер запущен и просто ожидает соединения от клиента.
Подключение к удаленной системе с вашего локального компьютера
В вашей локальной системе Linux уже должен быть установлен клиент SSH. Если нет, вы всегда можете установить его, используя следующую команду в Ubuntu:
Чтобы подключиться к вашей системе Ubuntu, вам необходимо знать IP-адрес компьютера и использовать команду ssh, например:
Измените username на своего фактического пользователя в системе и address на IP-адрес вашего сервера Ubuntu.
Если вы не знаете IP-адрес своего компьютера, вы можете ввести ip a в терминале сервера и проверить вывод. У вас должно получиться что-то вроде этого:
Использование «ip a» для поиска IP-адреса
Как видно здесь, мой IP-адрес 192.168.2.54. Давайте попробуем подключиться, используя формат имя username@adress.
При первом подключении к серверу SSH он запросит разрешение на добавление хоста. Введите да и нажмите Enter, чтобы продолжить.
Первое подключение к серверу
Сразу же SSH сообщает вам, что хост был добавлен навсегда, а затем запрашивает пароль, назначенный для имени пользователя. Введите пароль и еще раз нажмите Enter.
Хост добавлен, теперь введите пароль
И вуаля! Вы войдете в свою систему Ubuntu удаленно!
Теперь вы можете работать в терминале удаленной системы в обычном режиме.
Закрытие SSH-соединения
Чтобы закрыть соединение, вам просто нужно ввести exit, и оно сразу же закроет его, не запрашивая подтверждения.
Закрытие соединения
Остановка и отключение SSH в Ubuntu
Если вы хотите остановить службу SSH, вам понадобится эта команда:
Это остановит службу, пока вы ее не перезапустите или пока система не будет перезагружена. Чтобы перезапустить его, введите:
Теперь, если вы хотите отключить его запуск во время загрузки системы, используйте это:
Это не остановит работу службы во время текущего сеанса, а только загрузку во время запуска. Если вы хотите, чтобы он снова запускался во время загрузки системы, введите:
Другие клиенты SSH
Инструмент ssh включен в большинство систем * nix, от Linux до macOS, но это не единственные существующие варианты, вот пара клиентов, которые можно использовать из других операционных систем:
- PuTTY — это бесплатный SSH-клиент для Windows с открытым исходным кодом. Он полон функций и очень прост в использовании. Если вы подключаетесь к своей машине Ubuntu со станции Windows, PuTTY — отличный вариант.
- JuiceSSH — потрясающий инструмент для пользователей Android. Если вы в пути и вам нужен мобильный клиент для подключения к вашей системе Ubuntu, я настоятельно рекомендую попробовать JuiceSSH. Он существует уже почти 10 лет, и его можно использовать бесплатно.
- И, наконец, Termius доступен для Linux, Windows, macOS, iOS и Android. У него есть бесплатная версия, а также несколько дополнительных опций. Если у вас много серверов и вы работаете с командами, использующими общие соединения, Termius — хороший вариант для вас.
Заключение
С помощью этих инструкций вы можете настроить SSH в качестве серверной службы в системе Ubuntu, чтобы иметь возможность удаленно и безопасно подключаться к вашему компьютеру для работы с командной строкой и выполнения любых необходимых задач.