- Пользователь root может авторизоваться в SSH только по ключу
- Остальные пользователи могут авторизоваться в SSH по паролю
Как это можно решить? Никогда с подобным не приходилось связываться.
Текущий конфиг
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
#Match User root
PasswordAuthentication yes
GSSAPIAuthentication no
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes
UseDNS no-
Вопрос задан
А что если удалить у рута пароль, выставить
PermitRootLogin without-password
Запретить пустые пароли
PermitEmptyPasswords no
И коннектиться с ключом. Если я ничего не путаю, вы получите
1. Рут сможет приконнектиться только с ключом (пароля у него нет, а с пустым нельзя)
2. Остальные холят по паролям
PermitRootLogin yes -> PermitRootLogin no
И авторизовываться не под рутом. Вообще плохо рутом ходить куда-либо. Лучше отключить его, предварительно добавив вашего пользователя в sudoers и в группу с root-правами.
05 июл. 2023, в 15:07
1000 руб./за проект
05 июл. 2023, в 14:41
80000 руб./за проект
05 июл. 2023, в 14:30
1400 руб./в час
Минуточку внимания
В нашем мире опасность всегда угрожает тем, кто ее боится (Б. Шоу).

дним из основных шагов по усилению SSH является отключение входа по SSH на основе пароля.
Вы знаете, что вы можете использовать ssh с паролем root или другой учетной записи для удаленного входа на сервер Linux.
root@myserver:~# lastb | tail root ssh:notty 23.211.87.212 Wed Apr 1 02:12 - 02:12 (00:00) aw ssh:notty 36.121.175.68 Wed Apr 1 02:12 - 02:12 (00:00) fx ssh:notty 133.23.164.34 Wed Apr 1 02:12 - 02:12 (00:00) fx ssh:notty 133.23.164.34 Wed Apr 1 02:12 - 02:12 (00:00) root ssh:notty 167.22.123.74 Wed Apr 1 02:12 - 02:12 (00:00)
Вот почему вы должны использовать надежный пароль. Правильный способ борьбы с ними — использовать такой инструмент, как fail2ban. Другой способ — отключить аутентификацию на основе пароля, чтобы никто не мог подключиться через пароль для входа.
Таким образом, только те системы, чьи открытые ssh-ключи добавлены на сервер (так называемая аутентификация на основе ключей), смогут подключаться к серверу. Читайте о настройке конфигурации SSH.
Отключить аутентификацию по паролю SSH
Прежде чем сделать это, вы должны помнить следующее:
- Обязательно создайте пару ключей ssh на своем персональном/рабочем компьютере и добавьте этот открытый ключ SSH на сервер, чтобы по крайней мере вы могли войти на сервер.
- Отключение аутентификации на основе пароля означает, что вы не можете подключиться к серверу ssh со случайных компьютеров.
- Вы не должны терять свои ключи SSH. Если вы отформатируете свой персональный компьютер и потеряете ssh-ключи, вы никогда не сможете получить доступ к серверу.
- Если вы заблокированы, вы никогда не сможете получить доступ к вашему серверу.
Некоторые поставщики облачных серверов предоставляют VNC-консоль, которая может вам помочь.
Отключайте аутентификацию SSH на основе пароля только в том случае, если вы знакомы с SSH и другими концепциями системного администратора. Вы также должны знать, как использовать текстовый редактор на основе терминала, такой как Vim или Nano.
Ладно. Итак, теперь вы знаете риски, связанные с отключением входа по SSH с помощью пароля. Посмотрим, как это сделать.
Войдите в систему как root на ваш сервер Linux, используя аутентификацию на основе ключей. Используйте редактор, такой как Nano или Vim, для редактирования следующего файла:
/etc/ssh/sshd_config
Найдите следующую строку:
PasswordAuthentication yes
И измените его на:
PasswordAuthentication no
Если в начале этой строки есть символ # (закомментированный), удалите его.
Сохраните файл после внесения этих изменений и перезапустите службу SSH с помощью этой команды:
systemctl restart ssh
Вот и все. Вы успешно отключили аутентификацию на основе пароля в SSH.
Вопросы и предложения всегда приветствуются.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Remote ssh login using the root account is not a good Linux security practice. It poses a security challenge that can render your system vulnerable to attacks.
In this guide, we learn how to disable root login for SSH on Linux.
Why we should disable SSH root login?
A Linux system with remote root access can easily fall victim to brute force attacks. This is where an attacker uses automated scripts to guess the root login password.
Good practice recommends that you disable remote root login to your Linux machine. This prevents an attacker from remotely accessing your Linux server using the root password and, thus, having unlimited control over your system.
Prerequisites
Require access to a Linux system via console or ssh. Here for example we are using a Ubuntu system.
Step 1. Terminal Access to SSH Server
Access the terminal of your SSH server:
ssh [email protected]If you are logging in using the SSH key authentication method, type:
ssh -i your_private_key [email protected]_server_ipThe -i option specifies the SSH private key which will be used for authentication with the public key saved on the SSH server.
Step 2. Check auth. log file (Optional)
Once logged in to the server, view the contents of the auth.log file using the cat command as shown.
sudo cat auth.logYou should get output similar to what we have:
Jan 26 09:57:08 ubuntu sshd[255078]: Failed password for root from 138.68.226.175 port 53006 ssh2
Jan 26 09:57:09 ubuntu sshd[255082]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=211.112.187.197 user=root
Jan 26 09:57:09 ubuntu sshd[255078]: error: maximum authentication attempts exceeded for root from 138.68.226.175 port 53006 ssh2 [preauth]
Jan 26 09:57:09 ubuntu sshd[255078]: Disconnecting authenticating user root 138.68.226.175 port 53006: Too many authentication failures [preauth]
Jan 26 09:57:10 ubuntu sshd[255080]: Failed password for root from 38.60.204.121 port 58334 ssh2
Jan 26 09:57:11 ubuntu sshd[255082]: Failed password for root from 211.112.187.197 port 5197 ssh2
Jan 26 09:57:11 ubuntu sshd[255080]: error: maximum authentication attempts exceeded for root from 38.60.204.121 port 58334 ssh2 [preauth]The auth.log log file logs all authentication attempts made to a server. You will see multiple unknown and unauthorized requests being received by your server.
In the next step, we will make changes to the default ssh configuration file.
Step 3. Modifying SSH config file
The /etc/ssh/sshd_config is the default configuration file for the ssh daemon. It contains all the settings pertaining to the ssh service and handles all SSH connections.
Using your favorite text editor, open the sshd configuration file.
sudo /etc/ssh/sshd_config
Save the changes and close the file.
Remember editing PermitRootLogin value to no will completely disable ssh root login including SSH key-based login. Whereas setting PermitRootLogin to prohibit-password will disable root password login and at the same time allows ssh key-based login.
Step 4. Restart sshd service
sudo systemctl start sshdStep 5. Verifying SSH Root Login
ssh [email protected]_server_ipIf you are using the SSH key, the command will appear as shown.
ssh -i your_private_key [email protected]_server_ipIn both cases, you will get an authentication error confirming that root login has been disabled.

Conclusion
In this guide, we have demonstrated how to disable remote root login using the SSH protocol.






