Should the sudo
command or elevated privileges be used with Git?
You should not be using the sudo
command or elevated privileges, such as administrator permissions, with Git. If you have a very good reason you must use sudo
, then ensure you are using it with every command (it’s probably just better to use su
to get a shell as root at that point). If you generate SSH keys without sudo
and then try to use a command like sudo git push
, you won’t be using the same keys that you generated.
Check that you are connecting to the correct server
Typing is hard, we all know it. Pay attention to what you type; you won’t be able to connect to «githib.com» or «guthub.com». In some cases, a corporate network may cause issues resolving the DNS record as well.
To make sure you are connecting to the right domain, you can enter the following command:
$ ssh -vT git@github.com
> OpenSSH_8.1p1, LibreSSL 2.7.3
> debug1: Reading configuration data /Users/YOU/.ssh/config
> debug1: Reading configuration data /etc/ssh/ssh_config
> debug1: /etc/ssh/ssh_config line 47: Applying options for *
> debug1: Connecting to github.com port 22.
The connection should be made on port 22, unless you’re overriding settings to use SSH over HTTPS.
Always use the «git» user
All connections, including those for remote URLs, must be made as the «git» user. If you try to connect with your GitHub username, it will fail:
$ ssh -T GITHUB-USERNAME@github.com
> Permission denied (publickey).
If your connection failed and you’re using a remote URL with your GitHub username, you can change the remote URL to use the «git» user.
You should verify your connection by typing:
$ ssh -T git@github.com
> Hi USERNAME! You've successfully authenticated...
Make sure you have a key that is being used
- Open TerminalTerminalGit Bash.
- Verify that you have a private key generated and loaded into SSH.
# start the ssh-agent in the background $ eval "$(ssh-agent -s)" > Agent pid 59566 $ ssh-add -l -E sha256 > 2048 SHA256:274ffWxgaxq/tSINAykStUL7XWyRNcRTlcST1Ei7gBQ /Users/USERNAME/.ssh/id_rsa (RSA)
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
-
If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background $ eval "$(ssh-agent -s)" > Agent pid 59566
If you are using another terminal prompt, such as Git for Windows, turn on ssh-agent:
# start the ssh-agent in the background $ eval $(ssh-agent -s) > Agent pid 59566
-
Verify that you have a private key generated and loaded into SSH.
$ ssh-add -l -E sha256 > 2048 SHA256:274ffWxgaxq/tSINAykStUL7XWyRNcRTlcST1Ei7gBQ /Users/USERNAME/.ssh/id_rsa (RSA)
- Open TerminalTerminalGit Bash.
- Verify that you have a private key generated and loaded into SSH.
$ ssh-add -l -E sha256 > 2048 SHA256:274ffWxgaxq/tSINAykStUL7XWyRNcRTlcST1Ei7gBQ /Users/USERNAME/.ssh/id_rsa (RSA)
The ssh-add
command should print out a long string of numbers and letters. If it does not print anything, you will need to generate a new SSH key and associate it with GitHub.
Tip: On most systems the default private keys (~/.ssh/id_rsa
and ~/.ssh/identity
) are automatically added to the SSH authentication agent. You shouldn’t need to run ssh-add path/to/key
unless you override the file name when you generate a key.
Getting more details
You can also check that the key is being used by trying to connect to git@github.com
:
$ ssh -vT git@github.com
> ...
> debug1: identity file /Users/YOU/.ssh/id_rsa type -1
> debug1: identity file /Users/YOU/.ssh/id_rsa-cert type -1
> debug1: identity file /Users/YOU/.ssh/id_dsa type -1
> debug1: identity file /Users/YOU/.ssh/id_dsa-cert type -1
> ...
> debug1: Authentications that can continue: publickey
> debug1: Next authentication method: publickey
> debug1: Trying private key: /Users/YOU/.ssh/id_rsa
> debug1: Trying private key: /Users/YOU/.ssh/id_dsa
> debug1: No more authentication methods to try.
> Permission denied (publickey).
In that example, we did not have any keys for SSH to use. The «-1» at the end of the «identity file» lines means SSH couldn’t find a file to use. Later on, the «Trying private key» lines also indicate that no file was found. If a file existed, those lines would be «1» and «Offering public key», respectively:
$ ssh -vT git@github.com
> ...
> debug1: identity file /Users/YOU/.ssh/id_rsa type 1
> ...
> debug1: Authentications that can continue: publickey
> debug1: Next authentication method: publickey
> debug1: Offering RSA public key: /Users/YOU/.ssh/id_rsa
Verify the public key is attached to your account
You must provide your public key to GitHub to establish a secure connection.
-
Open Terminal.
-
Start SSH agent in the background.
$ eval "$(ssh-agent -s)" > Agent pid 59566
-
Find and take a note of your public key fingerprint.
$ ssh-add -l -E sha256 > 2048 SHA256:274ffWxgaxq/tSINAykStUL7XWyRNcRTlcST1Ei7gBQ /Users/USERNAME/.ssh/id_rsa (RSA)
-
In the upper-right corner of any page, click your profile photo, then click Settings.
-
In the «Access» section of the sidebar, click SSH and GPG keys.
-
Compare the list of SSH keys with the output from the
ssh-add
command.
-
Open the command line.
-
Start SSH agent in the background.
$ ssh-agent -s > Agent pid 59566
-
Find and take a note of your public key fingerprint.
$ ssh-add -l -E sha256 > 2048 SHA256:274ffWxgaxq/tSINAykStUL7XWyRNcRTlcST1Ei7gBQ /Users/USERNAME/.ssh/id_rsa (RSA)
-
In the upper-right corner of any page, click your profile photo, then click Settings.
-
In the «Access» section of the sidebar, click SSH and GPG keys.
-
Compare the list of SSH keys with the output from the
ssh-add
command.
-
Open Terminal.
-
Start SSH agent in the background.
$ eval "$(ssh-agent -s)" > Agent pid 59566
-
Find and take a note of your public key fingerprint. If you’re using OpenSSH 6.7 or older:
$ ssh-add -l > 2048 a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/USERNAME/.ssh/id_rsa (RSA)
If you’re using OpenSSH 6.8 or newer:
$ ssh-add -l -E md5 > 2048 MD5:a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/USERNAME/.ssh/id_rsa (RSA)
-
In the upper-right corner of any page, click your profile photo, then click Settings.
-
In the «Access» section of the sidebar, click SSH and GPG keys.
-
Compare the list of SSH keys with the output from the
ssh-add
command.
If you don’t see your public key in GitHub, you’ll need to add your SSH key to GitHub to associate it with your computer.
Warning: If you see an SSH key you’re not familiar with on GitHub, delete it immediately and contact GitHub Support, for further help. An unidentified public key may indicate a possible security concern. For more information, see «Reviewing your SSH keys.»
-
Главная
-
Инструкции
-
Linux
-
Как исправить ошибку аутентификации SSH
Основные механизмы аутентификации пользователей при подключении через SSH — проверка пароля и сверка ключей. Их можно применять вместе или по отдельности, это настраивается в файле конфигурации SSH. Оба способа надежные, но иногда при их использовании можно столкнуться с ошибкой authentication failed. В этой статье разберемся, какие у этого сбоя могут быть причины и как их устранить.
В чем суть ошибки
У сообщения «authentication failed» перевод на русский предельно простой. Этот вывод в терминале говорит о том, что аутентификация пользователя не удалась.
Аутентификация — это проверка подлинности. Например, у вас есть сервер на cloud.timeweb.com. Вы настроили SSH для удаленного подключения. Чтобы система защиты вас пропустила, нужно пройти процедуру аутентификации – подтвердить, что это действительно вы.
Метод проверки подлинности закреплен в конфигурационном файле SSH. По умолчанию это аутентификация по паролю.
Другой вариант — использование пары SSH-ключей для проверки подлинности. В таком случае у пользователя на компьютере хранится закрытая часть ключа. На сервере располагается открытая часть. При попытке установить соединение эти части сравниваются. При совпадении доступ открывается. Если совпадения нет, появляется сообщение об ошибке — например, следующая ошибка SSH:
Permission denied (publickey)
Но причины появления ошибки не ограничиваются только неправильным паролем или не теми ключами. Сбой может возникать также из-за повреждения системных файлов или неверно выставленных прав доступа.
Ниже разберемся с наиболее частыми ситуациями.
Ошибка при использовании пароля
Обычно проблемы возникают из-за неверного имени пользователя или пароля. Также стоит обратить внимание на конфигурацию сервера — может стоять запрет на аутентификацию через пароль. Как это проверить:
- Откройте файл конфигурации на сервере. Он находится по пути /etc/ssh/sshd_config.
- Найдите строку PasswordAuthentication. По умолчанию у неё значение `yes`. Это значит, что проверка по паролю разрешена.
- Если в вашем файле конфигурации параметр PasswordAuthentication имеет значение `no`, то подключиться по паролю не получится. Чтобы исправить ситуацию, измените значение на `yes`.
С паролем связано и появление ошибки su authentication failure. Вернее, с отсутствием парольной проверки у пользователя root. Если при такой конфигурации выполнить команду `su` без параметров, то вернется ошибка. Чтобы ее устранить, достаточно назначить пользователю root парольную защиту.
Ошибка при использовании ключей
Одна из самых распространенных проблем — использование не тех ключей при установке соединения. Часто это происходит, если с одного компьютера приходится подключаться к разным хостам. Самый простой способ не запутаться — давать понятные названия с указанием на то, для каких целей вы используете файлы аутентификации.
Использование большого количества ключей без явного указания нужного приводит еще к одной ошибке:
Too many authentication failures for user
Причина сбоя — превышение числа попыток. Это случается из-за того, что SSH-клиент пытается подключиться к хосту, используя все доступные ключи. Исправить ситуацию можно с помощью опций IdentitiesOnly и IdentityFile. Пример запроса на подключение:
ssh -o IdentitiesOnly=yes
-o IdentityFile=id1.key
user@example.com
Чтобы каждый раз не прописывать это в командной строке при подключении, можно указать необходимую настройку в конфигурационном файле SSH ~/.ssh/config. Пример такой настройки:
Host 192.168.3.44
IdentityFile ~/.ssh/id_rsa
Host *
IdentitiesOnly=yes
В этом случае SSH будет использовать только идентификаторы, указанные в файлах ssh_config, плюс идентификатор, указанный в командной строке. Идентификаторы, предоставленные агентом, будут игнорироваться.
При использовании ssh-ключей может возникнуть еще одна ошибка:
Permission denied (publickey, password)
Ее причиной может быть ввод неверной ключевой фразы.
Если вы потеряете ключевую фразу, восстановить ее будет невозможно. Вам нужно будет сгенерировать новую пару значений для Secure Shell.
Восстановление открытого ключа
Если у вас есть закрытый ключ, но вы потеряли открытую часть, то эту проблему можно решить стандартными средствами OpenSSH.
Самый просто способ — использовать утилиту ssh-keygen.
Запустите терминал и выполните команду:
ssh-keygen -y -f ~/.ssh/id_rsa
Здесь ~/.ssh/id_rsa — это путь к закрытому части, которая хранится на компьютере. В ответ вы получите последовательность символов. Это и есть открытая часть, которую необходимо добавить на сервер.
В среде Windows решить ту же задачу можно с помощью утилиты PuTTYgen, которая входит в набор PuTTY. В ней есть кнопка Load, через которую вы можете загрузить закрытый ключ. Для этого нужно лишь знать директорию, в которой он хранится на компьютере.
После импорта вы увидите окно с полем `Public key for…`. В нём отобразится открытая часть, которую можно скопировать и отправить на сервер.
Восстановить закрытую часть по открытой нельзя — это противоречит основам безопасности.
На что еще обратить внимание
У понятия «authentication failed» перевод дает весьма общее представление о причине сбоя. Проблема может крыться не только в пароле или ключах. Значение имеют также выставленные права доступа и алгоритмы шифрования.
Неправильная конфигурация клиента
Распространенная ошибка — использование клиента SSH/SFTP (SSH, PuTTY, Filezilla) без правильной настройки всех необходимых параметров, таких как хост, порт, имя пользователя или закрытый ключ.
Другая частая проблема возникает, когда вы используете неподдерживаемый сертификат. Например, пытаетесь добавить в PuTTY файл ключа *.pem вместо файла ключа *.ppk.
Противоречия в файле конфигурации
Убедитесь, что в файле /etc/ssh/sshd_config установлены параметры, которые не противоречат друг другу. Такое может быть, например, при отключении парольной проверки или запрете на подключение для пользователя root.
Распространенный пример конфликта: у параметра PasswordAuthentication установлено значение `yes`, а у параметра PermitRootLogin — значение `no` или `without-password`. Из-за этого сервер не понимает, как проверять пользователей, и не пускает никого.
Настройка прав доступа
У OpenSSH строгие правила к тому, кто должен быть владельцем файлов и какие на них должны быть выставлены права доступа.
Убедитесь, что на сервере выставлены следующие доступы:
- ~./ssh – 700.
- ~./ssh принадлежит текущему аккаунту.
- ~/.ssh/authorized_keys – 600.
- ~/.ssh/authorized_keys принадлежит текущему аккаунту.
На клиенте также проверьте разрешения следующих файлов:
- ~ / .ssh / config – 600.
- ~ / .ssh / id_ * – 600.
Почему важен владелец? Например, вы настраивали доступ через Secure Shell от имени одного пользователя, а затем пытаетесь подключиться под другим аккаунтом, у которого нет прав даже на чтение содержимого защищенных директорий с аутентификационными данными.
Использование устаревших алгоритмов
В OpenSSH начиная с седьмой версии не поддерживаются старые ключи, которые используют алгоритм цифровой подписи — DSA. Ключи ssh-dss считаются слишком слабыми для того, чтобы можно было доверять им защиту подключения к серверу.
Если у вас старые ключи, оптимальное решение — сгенерировать и добавить на хосты новые, которые основаны на более стойких алгоритмах.
Есть и альтернатива, но пользоваться ей придется на свой страх и риск. Речь идет об изменении файла конфигурации /etc/ssh/sshd_config. Если установить параметру PubkeyAcceptedKeyTypes значение `+ssh-dss`, то можно будет использовать ключи, сгенерированные с помощью устаревшего алгоритма цифровой подписи.
Дополнительные опции могут понадобиться и на SSH-клиенте. Например, при подключении к серверу с ПО, которое давно не обновлялось. В частности, такие проблемы возникают при подключении к хостам на CentOS 6, поддержка которой прекращена в конце 2020 года. Чтобы исправить эту ошибку, необходимо добавить опцию `-oHostKeyAlgorithms=+ssh-dss`:
ssh -oHostKeyAlgorithms=+ssh-dss user@legacyhost
Ошибки на сторонних сервисах
Проблемы аутентификации могут возникать и при использовании сторонних сервисов. Например, при подключении к VK API пользователи сталкиваются с сообщением user authorization failed invalid session
. Устранить такой сбой самостоятельно не получится — нужно обращаться в поддержку.
Заключение
Причина ошибки аутентификации может быть как на стороне клиента, так и на стороне сервера. Начинайте диагностику с самого простого: проверьте правильность имени пользователя и пароля, если он используется, выбор SSH-ключа в агенте. Если это не помогает устранить сбой, проверьте конфигурацию подключения и права доступа к файлам, которые OpenSSH использует для проверки подлинности пользователей.
We’ve all been there. You try to connect to your VPS, only to run into the dreaded permission denied (publickey)
error. Unfortunately, the reason for this differs, which can make troubleshooting harder, but generally the issue falls into four categories:
- You’re trying to connect to the wrong server
- Your local machine doesn’t have a matching key for your VPS server
- Your key isn’t in the authorized_keys file on your VPS server
- Your local machine has too many keys
Let’s run through the troubleshooting process to determine what’s creating your ssh permission denied
error and solve the root cause:
Run ssh -vvv [email protected] for more info
You can save a lot of time by determining why you can’t connect before you proceed. The following command will show you exactly what SSH is doing when you initiate a connection with your VPS server:
ssh -vvv [email protected]
Naturally, you should replace your.vps.ip
with the relevant IP address, which can be found in your control panel. Note down any output.
Make sure you’re connecting to the right server
It sounds basic, but it’s all too easy to do. You may have typed in a single digit of your server’s IP address wrong, or tried to connect to an old, expired server rather than your new one.
Double-check your credentials in your server control panel and be sure to copy and paste the information rather than typing it to ensure accuracy. You’d be surprised how easy it is to get two numbers mixed up.
Additionally, if you’ve just created the server, wait a few minutes a try again. Sometimes the server may indicate that it’s live even if it’s not quite ready for connection.
Try logging in with a password instead
For the short term, you may be able to log in with a password instead. This won’t work if you’re using PuTTy, or if you have password authentication disabled. You can give it a try with the following command:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no [email protected]
If you don’t have password authentication enabled, you can change that by clicking on the server in your BitLaunch control panel, selecting «Access», and entering a password. This will reboot your server and reset your password.
On your local machine, run ssh-keygen -R your.server.ip
to get rid of your old key.
Now, you should be able to connect to your server both if your local machine or VPS server didn’t have a matching key.
Manually add your SSH key to the VPS server
Now that you’re able to log in to your VPS server with a password, you can add an SSH key again.
Generate a key with:
ssh-keygen -t rsa
Then, if needed, copy it to your vps manually by typing ssh-copy-id [email protected]
.
Alternatively, copy it via SSH with:
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
You may want to make SSH keys your sole authentication method by editing the ssh_config file:
sudo nano /etc/ssh/sshd_config
Change PasswordAuthentication yes
to PasswordAuthentication no
, and save the changes.
Manually choose which key to use
If you have too many keys on your local machine, your ssh -vvv
output will have the output too many authentication failures for root
. You can bypass this by explicitly mentioning the correct key, like so:
ssh -i /home/bitlaunch/.shh/id_rsa [email protected]
If you’re still struggling with these steps and you’re a BitLaunch customer, reach out to our expert support, who will be happy to aid you further.
If you aren’t a BitLaunch customer, please feel free to sign up for a bitcoin vps today.
Introduction
The SSH Permission denied error appears after permission-related settings are modified on the SSH server. Usual scenarios include a new package installation or the creation of new users.
In this tutorial, you will learn how to troubleshoot the SSH Permission denied error and reconnect to your SSH server.
Prerequisites
- SSH client on the local machine and SSH server on the remote system
- A user account to access the remote server (for password-based login)
- A user account with sudo or root privileges
The SSH Permission denied error appears when trying to SSH into a server:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
Following the Permission denied statement, the bracket contains the attempted authentication methods that failed at the initiation of the connection. The error suggests that the public key is the issue, which is misleading.
One reason for the error may be sshd_config
, the file that contains SSH server configuration. The other possibility is that the authorized_keys
file has insufficient permissions. This file contains the list of public keys for the clients allowed to SSH into the server. Consequently, the system’s inability to read from the file results in the Permission denied error.
How to fix SSH Permission denied
Both solutions contain steps you need to perform on the server-side. Start by opening the terminal on your server and proceed with one of the solutions below.
Solution 1: Enable Password Authentication
If you want to use a password to access the SSH server, a solution for fixing the Permission denied error is to enable password login in the sshd_config
file.
To do this, open the file in a text editor. This example uses the nano editor:
sudo nano /etc/ssh/sshd_config
In the file, find the PasswordAuthentication
line and make sure it ends with yes
.
Find the ChallengeResponseAuthentication
option and disable it by adding no
.
If lines are commented out, remove the hash sign #
to uncomment them.
Save the file and exit.
Restart the SSH service by typing the following command:
sudo systemctl restart sshd
Solution 2: Change File System Permissions
Using the password-based login as the SSH authentication method is not recommended due to security concerns. Therefore, the following solution may be preferable since it troubleshoots the public key authentication method.
First, open the sshd_config
file using a text editor:
sudo nano /etc/ssh/sshd_config
In the file, make sure the following options are set as follows:
PermitRootLogin no
PubkeyAuthentication yes
Note: The steps above are considered best security practices. If you need to use root login, set the relevant line to yes
.
Comment out the GSSAPI-related options by adding the hash sign at the beginning of the line:
#GSSAPIAuthentication yes
#GSSAPICleanupCredentials no
Also, make sure the UsePAM
line is set to yes
:
UsePAM yes
Save the file and restart the sshd service:
systemctl restart sshd
Now navigate to your home folder and check the permissions:
ls -ld
If your owner permissions are not set to read, write, and execute (drwx------
), use the chmod command to change them:
chmod 0700 /home/[your-username]
Now go to the .ssh
folder and recheck the permissions:
ls -ld
This directory should also have read, write, and execute permissions for the file owner. To enforce them, use chmod
again:
chmod 0700 /home/your_home/.ssh
The .ssh
folder contains the authorized_keys
file. Check its permissions with:
ls -ld authorized_keys
The file owner should have read and write permissions. To set them, use:
chmod 0600 /home/[username]/.ssh/authorized_keys
Now try logging in with the key pair again. The output below shows a successful login attempt.
Conclusion
This tutorial covered the steps necessary to troubleshoot the SSH Permission denied (publickey,gssapi-keyex,gssapi-with-mic) error. By completing the steps in the guide, you should fix the error and successfully SSH into your server.
This quick tutorial shows you how to fix ssh error “sign_and_send_pubkey: signing failed: agent refused operation Permission denied (publickey)” on Linux.
If you are trying to connect to the remote server via SSH, you might encounter permission denied error. This error may happen for a number of reasons. And the fix to this issue depends upon the exact reason behind the error.
In my case, I had the public and private keys stored on my Ubuntu 16.04 desktop. After Ubuntu 18.04 release, I decided to upgrade to this newer version. I prefer a fresh install over distribution upgrades.
So, I made a backup of the main folders of my Home directory including the .ssh folder that had public and private keys on an external disk.
Once installed, I enabled SSH on Ubuntu 18.04 and restored everything including the SSH keys.
Now when I tried to connect to the remote server using ssh, I thought it would work straightaway because I had the same public and private keys.
But it didn’t work. SSH gave me this error:
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey).
If you are in a similar situation where you copied your SSH keys from another source, let me show you how to fix this SSH error.
Correct file permissions on ~/.ssh folder and its content
As a rule of thumb, you can set the following permissions on the ssh directory and its files (private keys, public keys, known_hosts, ssh config file etc)
Element | Permission |
---|---|
.ssh directory | 700 ((drwx——) |
public keys | 644 (-rw-r—r—) |
private keys | 600 (-rw——-) |
authorized_keys | 600 (-rw——-) |
known_hosts | 600 (-rw——-) |
config | 600 (-rw——-) |
You may not have all the files but you must have public and private keys here.
Now let’s see how to change the file permission on the ssh keys and other files.
Fixing Permission denied (publickey) error
So the problem lies with file permissions here. You see, when I copied the files, the USB was in Microsoft’s FAT file format. This file doesn’t support the UNIX/Linux file permissions.
And hence the permissions on the copied ssh keys were changed to 777.
For SSH, the file permissions are too open. It’s simply not allowed to have 777 permissions on the public or private keys. And this is why SSH refused connection here.
ls -l .ssh
-rwxrwxrwx 1 abhishek abhishek 1766 Nov 12 2017 id_rsa
-rwxrwxrwx 1 abhishek abhishek 398 Nov 12 2017 id_rsa.pub
-rwxrwxrwx 1 abhishek abhishek 4214 Sep 21 21:39 known_hosts
The private key should have read and write permissions only for the user and no other permissions for the group and others.
You should change the permission using the chmod command:
chmod 600 ~/.ssh/id_rsa
Similarly, the public key shouldn’t have write and execute permissions for group and other.
chmod 644 ~/.ssh/id_rsa.pub
Now that you have put the correct permissions, you can connect to ssh again. At this time, it will ask your admin password to unlock the keys. Enter your admin password and you should be good to go.
This also taught me a lesson that copy-pasting files is a bad idea and a proper backup should be made else all the files will have the dangerous 777 permissions on them. I had to recursively change the file permissions on the entire Home directory and trust me, it wasn’t a pretty thing to do.
As I said earlier, there can be various reasons for this error. For the issue related to open file permission, this fix should help you fix the Permission denied (publickey) error with SSH. If you are interested, you can read more about SSH basics.
Let me know in the comment section if the fix worked for you or not. Also suggest your opinion on copying ssh keys on other computers.
Creator of Linux Handbook and It’s FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries from Agatha Christie and Sherlock Holmes to Columbo & Ellery Queen.
When I access my server via SSH, it returns permission denied (publickey) error in my DigitalOcean Droplet. What’s wrong with my server?
That was a recent support ticket received at our DigitalOcean Managed Services department where we resolve support queries for web hosts.
Droplet owners often use key based authentication to improve security on their servers.
But, what happens if these SSH keys are not configured properly? Result is, server denies access and kicks you out with errors.
One such error is “Permission denied (publickey)“.
Today, we’ll discuss the top 4 reasons of this error and how our Cloud Experts fix them.
Permission denied (publickey) in DigitalOcean – What’s this?
Before we go to the reasons of this error, let’s get an idea of this error first.
A key based authentication needs a private key and a public key pair.
The public key is placed on the Droplet while the private key is placed on the user’s computer.
And, users submit this private key to authenticate and connect via SSH.
The error “Permission denied (publickey)” clearly shows that there is a problem with the SSH keys used for authentication.
Since publickey is shown in the error message, it doesn’t mean that the public key is the problem.
Actually, this error shows that the public key of the Droplet rejects the private key provided during authentication.
So, our Support Engineers recreate the problem by connecting to the server via SSH in debug mode.
ssh -vvv 195.xxx.12x.15x
It will therefore give a detailed trace of the connection that will help us to analyze the problem.
In addition to that, we check the SSH logs(/var/log/auth.log or /var/log secure) to see why this error occurred.
Permission denied (publickey) in DigitalOcean – Causes and Fixes
Now, let’s see the main reasons for this error and how our Support Experts fix them.
1) Wrong private key
Most often, this error comes up when Droplet owners use the wrong private key to connect to the server.
Similarly, sometimes Droplet owners change the private key name, but use the wrong key name when connecting via SSH.
How we fix?
In this case, the easiest way to confirm that the private key causes problems, is to create a new key pair, and connect with the new set of keys.
If that works, we’ll update the customers to check and correct their private key file and location.
But, we always recommend that customers create a new key pair to connect to the server.
2) Incorrect SSH key permissions
SSH enforces strict permission on key files by default.
In other words, if any of the files in the .ssh folder can be written by anyone other than the user, then SSH refuses to authenticate.
Because, hackers can easily modify/replace key files, if the parent directories can be written by others.
Similarly, there are cases in which users don’t have sufficient permission or ownership to read the private and public key.
In both cases, the DigitalOcean server shows Permission denied (publickey).
How we fix?
The ideal permission of .ssh folder should be 700 and the files in .ssh folder should be 600.
So, our Hosting Engineers first check the permission and ownership of the .ssh folder and the files in this folder.
And, if any permission or ownership related errors are noted, we correct them immediately.
Most importantly, we ensure that the permission of the .ssh/authorized_keys file is 600, because it’s the file where public key is stored.
3) Missing public key in remote host
The public key generated at the localhost should be added to the remote host for any new users created on the server.
This key pair is used by the remote host to identify the user’s machine while connecting via SSH.
Ideally, the public key should be stored at /home/user/.ssh/authorized_keys in DigitalOcean Droplets.
However, we’ve seen cases where Droplet owners fail to add this key to the remote host.
As a result, SSH kicks them out with the error permission denied (publickey).
How we fix?
Our Hosting Engineers first verify the authorized_keys file location in SSH configuration file /etc/ssh/sshd_config.
To add the user’s public key to this file, we open the .ssh/authorized_keys file and copy the public key.
Most importantly, we restart the SSH service to reflect the changes.
In most cases, we recommend that users use the ssh-copy-id utility(if it is supported) to copy the public key to the remote host, because it automatically add/create the required files and directories and assign proper permissions.
So, there is no chance for users to mess up the permissions.
Otherwise, we need to manually add the SSH key to the remote host.
4) Incorrect username/hostname
Similarly, when users use incorrect SSH username, incorrect IP or host, they will come up with the error permission denied (publickey).
This is because, there will not be a matching public key for the private key that users submit.
How we fix?
Our Support Engineers try to create a new key pair in such cases. If that doesn’t work, we check the SSH connection settings.
We ensure that there is no typo in hostname and it resolves to the customer’s Droplet IP using the dig command.
dig server.hostname.com
Additionally, we ensure that the IP address is up using the ping command.
ping IP_ADDRESS
Conclusion
In short, DigitalOcean SSH error ‘permission denied (publickey)’ can occur due to wrong SSH key permissions, wrong SSH username, and more. Today, we’ve discussed the top 4 reasons for this error and how our Cloud Experts fix them.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
SEE SERVER ADMIN PLANS
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;