Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a27919a1fa3248b • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a27919c3d3577b5 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Как включить SSH в Ubuntu 20.04
Secure Shell (SSH) — это сетевой протокол, используемый для безопасного соединения между клиентом и сервером. Каждое взаимодействие между сервером и клиентом зашифровано.
В этом руководстве объясняется, как включить SSH на компьютере с Ubuntu.
Включение SSH позволит вам удаленно подключаться к вашей системе и выполнять административные задачи. Вы также сможете безопасно передавать файлы через scp и sftp .
Включение SSH в Ubuntu
По умолчанию при первой установке Ubuntu удаленный доступ через SSH не разрешен. Включение SSH в Ubuntu довольно просто.
Выполните следующие шаги от имени пользователя root или пользователя с правами sudo для установки и включения SSH в вашей системе Ubuntu:
Откройте терминал с помощью Ctrl+Alt+T и установите пакет openssh-server :
При появлении запроса введите свой пароль и нажмите Enter, чтобы продолжить установку.
После завершения установки служба SSH запустится автоматически. Вы можете убедиться, что SSH работает, набрав:
Вывод должен сообщить вам, что служба запущена и разрешена для запуска при загрузке системы:
Нажмите q чтобы вернуться в командную строку.
Ubuntu поставляется с инструментом настройки брандмауэра под названием UFW. Если в вашей системе включен брандмауэр , обязательно откройте порт SSH:
Это оно! Теперь вы можете подключиться к своей системе Ubuntu через SSH с любого удаленного компьютера. В системах Linux и macOS по умолчанию установлены клиенты SSH. Для подключения с компьютера Windows используйте SSH-клиент, например PuTTY .
Подключение к SSH-серверу
Чтобы подключиться к вашей машине Ubuntu по локальной сети, вызовите команду ssh, за которой следует имя пользователя и IP-адрес в следующем формате:
Если вы не знаете свой IP-адрес, вы можете легко найти его с помощью команды ip :
Как видно из выходных данных, IP-адрес системы — 10.0.2.15 .
Найдя IP-адрес, войдите на удаленный компьютер, выполнив следующую команду ssh :
При первом подключении вы увидите такое сообщение:
Введите yes и вам будет предложено ввести пароль.
После ввода пароля вы увидите сообщение Ubuntu по умолчанию:
Теперь вы вошли в систему на своей машине с Ubuntu.
Подключение к SSH за NAT
Чтобы подключиться к домашней машине с Ubuntu через Интернет, вам необходимо знать свой общедоступный IP-адрес и настроить маршрутизатор на прием данных через порт 22 и их отправку в систему Ubuntu, где работает SSH.
Чтобы определить общедоступный IP-адрес компьютера, к которому вы пытаетесь подключиться по SSH, просто перейдите по следующему URL-адресу: https://api.ipify.org .
Когда дело доходит до настройки переадресации портов , каждый маршрутизатор имеет свой способ настройки переадресации портов. Чтобы узнать, как настроить переадресацию портов, обратитесь к документации маршрутизатора. Короче говоря, вам нужно ввести номер порта, на который будут выполняться запросы (порт SSH по умолчанию — 22), и частный IP-адрес, который вы нашли ранее (с помощью команды ip a ) машины, на которой работает SSH.
После того, как вы нашли IP-адрес и настроили маршрутизатор, вы можете войти в систему, набрав:
Если вы открываете свою машину для доступа в Интернет, рекомендуется принять некоторые меры безопасности. Самый простой — настроить маршрутизатор на прием трафика SSH на нестандартный порт и пересылку его на порт 22 на машине, на которой запущена служба SSH.
Вы также можете настроить аутентификацию на основе ключа SSH и подключиться к компьютеру с Ubuntu без ввода пароля.
Отключение SSH в Ubuntu
Чтобы отключить SSH-сервер в вашей системе Ubuntu, просто остановите службу SSH, запустив:
Позже, чтобы снова включить его, введите:
Выводы
Мы показали вам, как установить и включить SSH на вашем Ubuntu 20.04. Теперь вы можете войти на свой компьютер и выполнять повседневные задачи системного администратора через командную строку.
Если вы управляете несколькими системами, вы можете упростить рабочий процесс, указав все свои подключения в файле конфигурации SSH . Изменение порта SSH по умолчанию добавляет дополнительный уровень безопасности вашей системе, снижая риск автоматических атак.
Для получения дополнительной информации о том, как настроить SSH-сервер, прочтите руководство по SSH / OpenSSH / настройке Ubuntu и официальную страницу руководства по SSH .
Introduction
you will need to configure it by editing the sshd_config file in the /etc/ssh directory.
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:
replace it with a line that looks like this:
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:
and replace them with:
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:
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:
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.
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.
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:
and change it to this:
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:
and replace it with:
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:
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