Permission denied publickey ssh ошибка windows

A «Permission denied» error means that the server rejected your connection. There could be several reasons why, and the most common examples are explained below.

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

  1. Open TerminalTerminalGit Bash.
  2. 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.

  1. 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
  2. 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)
  1. Open TerminalTerminalGit Bash.
  2. 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.

  1. Open Terminal.

  2. Start SSH agent in the background.

    $ eval "$(ssh-agent -s)"
    > Agent pid 59566
  3. 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)
  4. In the upper-right corner of any page, click your profile photo, then click Settings.

    Screenshot of GitHub's account menu showing options for users to view and edit their profile, content, and settings. The menu item "Settings" is outlined in dark orange.

  5. In the «Access» section of the sidebar, click SSH and GPG keys.

  6. Compare the list of SSH keys with the output from the ssh-add command.

  1. Open the command line.

  2. Start SSH agent in the background.

    $ ssh-agent -s
    > Agent pid 59566
  3. 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)
  4. In the upper-right corner of any page, click your profile photo, then click Settings.

    Screenshot of GitHub's account menu showing options for users to view and edit their profile, content, and settings. The menu item "Settings" is outlined in dark orange.

  5. In the «Access» section of the sidebar, click SSH and GPG keys.

  6. Compare the list of SSH keys with the output from the ssh-add command.

  1. Open Terminal.

  2. Start SSH agent in the background.

    $ eval "$(ssh-agent -s)"
    > Agent pid 59566
  3. 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)
  4. In the upper-right corner of any page, click your profile photo, then click Settings.

    Screenshot of GitHub's account menu showing options for users to view and edit their profile, content, and settings. The menu item "Settings" is outlined in dark orange.

  5. In the «Access» section of the sidebar, click SSH and GPG keys.

  6. 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.»

Here is a step-by-step guide that I used to get this to work.

Platform: Windows 7

Install msysgit from http://msysgit.github.io/

During installation, accept all of the default options, except when the ‘Select Components’ option appears. When this appears, select ‘Git Bash Here’ option. Although this isn’t necessary, it adds a nice context menu when working in Windows Explorer that I found to be very helpful.

enter image description here

Once msysgit is installed Git Bash will also be installed. Open Git Bash in one of 2 ways:

  • Click the Windows Start key and start typing Git Bash
  • Or, right click somewhere (e.g. your Desktop) and select Git Bash Here. This option is only available if ‘Git Bash Here’ context menu was installed.

In Git Bash’s command window, enter this:

$ ssh-keygen -t rsa

When asked to enter a file name, just accept the default. Choose a strong passphrase when prompted, and your public key should now be saved. Your screen should look like this:

enter image description here

Go open the public key file in Notepad. The file should reside here:

C:Users{username}.sshid_rsa.pub

Copy all of the content in the file to your clipboard, then go to GitHub’s SSH settings page:

https://github.com/settings/ssh

Choose ‘Add SSH key’, enter a useful ‘Title’ and paste the content into the ‘Key’ textarea.

To simplify your life, you can use the SSH agent to save your passphrase so that you don’t need to remember it. To do so, type this into Git Bash:

$ eval `ssh-agent -s`
$ ssh-add ~/.ssh/id_rsa

You’ll be prompted to enter your passsphrase. If everything succeeds, your identity will have been added. Note: this passphrase will be forgotten as soon as you close your shell. I’m not sure how to make this persist across sessions, but maybe someone can help?

To test that everything works, enter this into Git Bash:

$ ssh -T git@github.com

You should see a ‘success’ meesage.

Sources:

https://help.github.com/articles/generating-ssh-keys/

https://help.github.com/articles/working-with-ssh-key-passphrases/

explanation on why eval `ssh-agent -s` should be used instead of just ssh-agent -s

https://stackoverflow.com/a/17848593/188740

День добрый. Возник вопрос с авторизацией в Windows OpenSSH по ключу.
До этого несколько раз доводилось настраивать без ключей (только по паролю) и вроде бы все было ок.
В этот раз решил сделать авторизацию только по SSH-ключу и напоролся на Permission denied (publickey,keyboard-interactive).

Кратко о сервере:
Сервер — винда 10
Юзер — локальная учетная запись (с правами администратора)
Публичный ключ лежит в authorized_keys в дирректории пользователя (C:UsersLocalUser.sshauthorized_keys).
Всевозможные перезапуски и перезагрузки были.
OpenSSH сервер установлен: (на всякий случай испробованы оба варианта)
1) Параметры -> Приложения -> Дополнительные компоненты -> Сервер OpenSSH
2) Через PowerShell согласно официальной инструкции

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

Windows inbox Beta version currently supports one key type (ed25519).

До этого использовал RSA-ключи и в логе мелькала информация о ключах в духе

debug1: identity file C:\Users\LocalUser/.ssh/id_rsa type 0
debug1: identity file C:\Users\LocalUser/.ssh/id_ed25519 type -1

Под каждым из которых была строка о том что файл не найден.

После чтения той issue стал использовать ed25519-ключ, теперь стало так:

debug1: identity file C:\Users\LocalUser/.ssh/id_ed25519 type 3
debug3: Failed to open file:C:/Users/LocalUser/.ssh/id_ed25519-cert error:2
debug3: Failed to open file:C:/Users/LocalUser/.ssh/id_ed25519-cert.pub error:2
debug1: identity file C:\Users\LocalUser/.ssh/id_ed25519-cert type -1

Собственно в конечном счете в логе мелькает (если я правильно понимаю) отправка ключа

debug1: Offering public key: C:\Users\LocalUser/.ssh/id_ed25519 ED25519 SHA256:xKMs9i1ZJyeQjvIY3jL2WIZnGNwOr6v/7QLUPu9t2Nw explicit
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51

Однако после него SSH пытается пройти авторизацию по другим включенным способам авторизации — если по паролю включена — спрашивает пароль (даже в случае когда ключ явно указан), если выключена — сразу Permission denied (publickey,keyboard-interactive).

Подскажите в чем проблема в этом случае?

Полный лог c клиента доступен на https://gist.github.com/NEK-RA/e3656f98ca7e1b6c4d7… (т.к. если вставить его напрямую тут, будет превышен лимит в 10 000 символов в тексте вопроса)
UPD: По той же ссылке добавлен и лог сервера с небольшим отличием — на текущий момент не было доступа к нужному устройству, поэтому ситуация продублирована в виртуальной машине.

При первой загрузке/выгрузке изменений в/из Github часто возникает ошибка git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Данная статья раз и навсегда положит этим ошибкам конец!
Ошибка git@github.com: Permission denied (publickey)

Всё то, о чём пойдет речь ниже, можно посмотреть в этом видео

Открываем терминал в том месте где у вас лежит код, который вы хотите интегрировать в Github или Gitlab. Проверяем есть ли уже существующий SSH ключ, для этого вводим команду ниже:
ls -al ~/.ssh
Пример НЕсуществующего ключа SSH:
Пример несуществующего SSH

Пример существующего ключа SSH:
Пример существующего SSH
Если ключ существует переходите сразу к шагу 4 или создайте отдельный новый ключ специально для Github.

ШАГ 2. Генерация нового SSH ключа

  • Введите в терминале команду ниже:
    ssh-keygen -t ed25519 -C «your_email@example.com»
    Пояснения команды:

    ssh-keygen команда для генерации SSH ключа
    -t ed25519 алгоритм шифрования, по умолчанию алгоритм rsa, Github рекомендует использовать алгоритм ed25519
    -C значит «комментарий», все что после этой команды в кавычках будет комментарием
    «your_email@example.com» комментарий, замените на свой email в Github — это нужно чтобы различать SSH ключи между собой, их может быть несколько
  • Теперь нужно указать путь и название файла, можно оставить по умолчанию и нажать Enter, но давайте поменяем имя файла, чтобы понимать что он сгенерирован именно для Github!
    Скопируйте и вставьте путь по умолчанию, поменяйте имя файла и нажмите Enter.
    Ввод названия для SSH ключа
  • Далее нужно будет задать пароль (кодовую фразу) для нашего ключа, пропускаем этот шаг, просто два раза нажимаем Enter, иначе придется постоянно вводить этот пароль.
    Ввод пароля для SSH ключа
  • Если вы все сделали правильно будет примерно также, как на скриншоте ниже:
    Успешно сгенерированный SSH ключ

ШАГ 3. Добавление SSH ключа в SSH-agent

Не пропускайте этот шаг! Без него ничего работать не будет.

Что же такое SSH-agent на сайте habr.com вот такое описание: «ssh-agent — это менеджер ключей для SSH. Он хранит ваши ключи и сертификаты в памяти, незашифрованные и готовые к использованию ssh . Это избавляет вас от необходимости вводить пароль каждый раз, когда вы подключаетесь к серверу.»

  • Сначала запустим SSH-agent командой ниже:
    eval «$(ssh-agent -s)»
    надпись Agent pid 61 (у вас будет любое другое число) говорит о том, что агент успешно запущен!
    SSH-agent запущен
  • Добавьте SSH ключ в SSH агент командой ниже, предварительно поменяв название SSH ключа на ваше:
    ssh-add ~/.ssh/id_ed25519_github
    надпись примерная как на скрине ниже, говорит о том, что ключ успешно добавлен
    SSH ключ добавлен в SSH-agent
  • Добавим конфигурационный файл, чтобы SSH ключ автоматически добавлялся в SSH-agent, введите команду ниже, она создаст файл config, если он отсутствует:
    touch ~/.ssh/config
  • Теперь в созданный файл config добавим следующий текст, заменив id_ed25519_github на название своего ключа, если нужно:

    Host *
      AddKeysToAgent yes
      IdentityFile ~/.ssh/id_ed25519_github

    • Для пользователей MacOS вводим команду ниже, откроется обычный редактор текста, вставляем в него текст и сохраняем изменения
      open ~/.ssh/config
    • Для пользователей Windows вводим команду ниже и нажимаем Enter
      cat > ~/.ssh/config <<EOF
      далее вставить текст, нажать Enter, ввести команду ниже и нажать Enter
      EOF

      Настройка config для автоматического добавления SSH ключа в SSH-agent
  • Проверьте что текст был добавлен в файл config командой
    cat ~/.ssh/config
    должно быть как на скриншоте:
    Успешно добавленный текст в файл config

ШАГ 4. Добавление SSH в Github

Готово! Проверьте что ключ работает

Возвращаемся в наш терминал и вводим команду git pull, файлы должны загрузиться или как в моем случае должна появиться надпись, что все уже обновлено.
Успешное соединение по SSH ключу с Github

Спасибо за внимание!

  • Главная

  • Инструкции

  • Linux

  • Как исправить ошибку аутентификации SSH

Blog

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

Как Исправить Ошибку Аутентификации Ssh (2)

В чем суть ошибки

У сообщения «authentication failed» перевод на русский предельно простой. Этот вывод в терминале говорит о том, что аутентификация пользователя не удалась.

Аутентификация — это проверка подлинности. Например, у вас есть сервер на cloud.timeweb.com. Вы настроили SSH для удаленного подключения. Чтобы система защиты вас пропустила, нужно пройти процедуру аутентификации – подтвердить, что это действительно вы. 

Метод проверки подлинности закреплен в конфигурационном файле SSH. По умолчанию это аутентификация по паролю. 

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

Permission denied (publickey)

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

Ниже разберемся с наиболее частыми ситуациями. 

Ошибка при использовании пароля

Обычно проблемы возникают из-за неверного имени пользователя или пароля. Также стоит обратить внимание на конфигурацию сервера — может стоять запрет на аутентификацию через пароль. Как это проверить:

  1. Откройте файл конфигурации на сервере. Он находится по пути /etc/ssh/sshd_config.
  2. Найдите строку PasswordAuthentication. По умолчанию у неё значение `yes`. Это значит, что проверка по паролю разрешена.
  3. Если в вашем файле конфигурации параметр 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 использует для проверки подлинности пользователей.

Обновлено 07.04.2022

ssh logo

Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов в рунете Pyatilistnik.org. В прошлый раз мы с вами разобрали ошибку, что для устройства не установлены драйверы (код 28). Идем далее и сегодня хочу с вами поделиться практическими знаниями, по устранению ошибки в open ssh клиенте Windows. Звучит она вот так, что на секретный ключ id_rca bad permissions (WARNING: UNPROTECTED PRIVATE KEY FILE, Permission denied publickey). В результате подключиться не получается. Давайте переходить от слов к делу.

Как выглядит ошибка id_rsa bad permissions

В командной строке Windows при попытке подключения выскакивает ошибка:

Bad permissions. Try removing permissions for user: Pyatilistnik\seminivan (S-1-5-21-117609710-5564564-725645543-16185) on file C:/Users/barboskin/.ssh/id_rsa.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for ‘C:\Users\barboskin\.ssh\id_rsa’ are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key «C:\Users\barboskin\.ssh\id_rsa»: bad permissions
barboskin@178.15.24.44: Permission denied (publickey).

id_rca bad permissions

Как устранить ошибку Permission denied (publickey)

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

Используем скрипт PowerShell

Запустите в режиме администратора оснастку PowerShell ISE и запустите в нем такой скрипт.

# Устанавливаем переменную для ключевого файла:
New-Variable -Name Key -Value «$env:UserProfile.sshid_rsa»

# Удаляем наследование:
Icacls $Key /c /t /Inheritance:d

# Делаем владельцем файла текущего пользователя:
# Key’s within $env:UserProfile:
Icacls $Key /c /t /Grant ${env:UserName}:F

# Ключ вне $env:UserProfile:
TakeOwn /F $Key
Icacls $Key /c /t /Grant:r ${env:UserName}:F

# Удаляем всех пользователей, кроме владельца из ACL:
Icacls $Key /c /t /Remove:g Administrator «Authenticated Users» BUILTINAdministrators BUILTIN Everyone System Users

# Проверка:
Icacls $Key

# Удаляем переменную:
Remove-Variable -Name Key

Как устранить ошибку Permission denied

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

Редактирование ACL через графический интерфейс

Тут все просто, переходите в расположение файла:

C:Usersимя_пользователя.sshid_rsa

Щелкаем по файлу правым кликом, из контекстного меню выбираем пункт свойства и переходим на вкладку «Безопасность«. Нажмите кнопку «Дополнительно (Advanced)«

Права на id_rsa

Отключаем наследование и сохраняем текущие разрешения «Преобразовать унаследованные разрешения в явные разрешения данного объекта (Convert inherited permission into explicit permissions on this object«.

Отключение наследования на файле id_rsa

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

Чистка списка доступа у файла

Сохраняем все, после этого у вас должна пропасть ошибка «id_rsa»: bad permissions» и «Permission denied (publickey)».

Используем скрипт командной строки

Во первых вам необходимо создать bat-файл. После чего запустите командную строку от имени администратора и запустите созданный ранее bat-файл.

# Установить переменную ключевого файла::
Set Key=»%UserProfile%.sshid_rsa»

::# Удалить наследование:
Icacls %Key% /c /t /Inheritance:d

::# Установить право собственности на владельца:
:: # Key’s within %UserProfile%:
Icacls %Key% /c /t /Grant %UserName%:F

:: # Ключ outside на %UserProfile%:
TakeOwn /F %Key%
Icacls %Key% /c /t /Grant:r %UserName%:F

::# Удалить всех пользователей, кроме владельца:
Icacls %Key% /c /t /Remove:g «Authenticated Users» BUILTINAdministrators BUILTIN Everyone System Users

::# Проверять:
Icacls %Key%

::# Удалить переменную:
set «Key=»

cmd установка прав на файл

На этом все. Мы рассмотрели три метода позволяющих исправить ошибки «id_rsa»: bad permissions» и «Permission denied (publickey)» при попытке установить ssh соединение через OpenSSH в Windows. С вами был Иван Сёмин, автор и создатель IT проекта Pyatilistni.org.

I am following the thread to set up SSH

But I get below error on 5th step

$ ssh -T git@github.com
Warning: Permanently added the RSA host key for IP address 'xxx.xx.xxx.xxx' to the list of known hosts.
Permission denied (publickey).

Below is the detailed log

$ ssh -vT git@github.com
$ ssh -vT git@github.com
OpenSSH_7.1p1, OpenSSL 1.0.2d 9 Jul 2015
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [192.30.252.128] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Kiran B/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/Kiran B/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.1
debug1: Remote protocol version 2.0, remote software version libssh-0.7.0
debug1: no match: libssh-0.7.0
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client chacha20-poly1305@openssh.com <implicit> none
debug1: kex: client->server chacha20-poly1305@openssh.com <implicit> none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-rsa 
SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /c/Users/Kiran B/.ssh/known_hosts:1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /c/Users/Kiran B/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /c/Users/Kiran B/.ssh/id_dsa
debug1: Trying private key: /c/Users/Kiran B/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/Kiran B/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).

Jakuje's user avatar

Jakuje

9,9825 gold badges31 silver badges34 bronze badges

asked Jan 5, 2016 at 10:23

Kiran B's user avatar

2

Create a SSH config file

How to add ssh key to github account?

And you all set to go :-)

Community's user avatar

answered Jan 10, 2016 at 3:07

CodeWizard's user avatar

Recently I faced same issue.

Maybe your ssh identities was deleted.
If run this command

ssh-add -l

You get this message «The agent has no identities.«


I recommended you, generate a new ssh key

ssh-keygen -t rsa -b 4096 -C «your github mail account»

  • [Press enter]
  • [Type a secure passphrase]
  • Enter same passphrase again

You get identification saved message.

Now, run this command,

ssh-add ~/.ssh/id_rsa

Enter your passphrase.


Copy your SSH RSA Key by

clip < ~/.ssh/id_rsa.pub

Now,
Goto your GitHub account > Settings > SSH Keys > New SSH Key and Paste the copied key.

Verify SSH connection with GitHub.

ssh -T git@github.com

Finally, you get this message,

Hi …! You’ve successfully authenticated, but GitHub does not provide shell access.

answered Mar 22, 2016 at 11:41

Love Bdsobuj's user avatar

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.

How to Fix the SSH Permission Denied Error

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)
The SSH Permission denied error appearing after a login attempt

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.

Editing the shhd_config file to enable password authentication to fix SH Failed Permission Denied (Publickey,Gssapi-Keyex,Gssapi-With-Mic)

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
Editing the shhd_config file to enable public key authentication

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
Editing the shhd_config file to comment out the GSSAPI-related options

Also, make sure the UsePAM line is set to yes:

UsePAM yes
Editing the shhd_config file to enable UsePAM

Save the file and restart the sshd service:

systemctl restart sshd

Now navigate to your home folder and check the permissions:

ls -ld
Checking home folder permissions

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
Checking the .ssh folder permissions

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
Checking the permissions of the authorized_keys file

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.

A successful SSH login attempt after troubleshooting

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.

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.


Posted:
05 Apr, 23


Updated:
05 Apr, 23



by Susith Nonis



4 Min

Troubleshooting SSH Permission Denied (publickey)

List of content you will read in this article:

SSH: A tool that many admins couldn’t imagine getting by without. It’s like a trusty wrench in the toolkit that helps keep the server wheels turning. But like any tool, it can sometimes refuse to cooperate, and you may need to do some troubleshooting to fix it. If you’ve ever encountered the Permission Denied (publickey) error, you know how frustrating it can be. It’s one of those pesky SSH errors that can ruin your day. But fear not, for we’re here to help you understand what causes it and, more importantly, how you can fix it. So, please grab a cup of coffee and let’s dive into some SSH problem-solving.

What is The SSH Permission Denied (publickey) Error?

Oh boy, the SSH Permission Denied (publickey) Error. It’s like the curse of the SSH universe. The error message makes you want to shake your fist at the computer and scream, «Why me?!» But fear not, my friends. I’m here to shed some light on this mysterious error.

In a nutshell, the SSH Permission Denied (publickey) Error occurs when your SSH connection gets rejected by a remote server because it doesn’t recognize your public key. 

It’s like getting into a high-security facility without the right access card. You’ll just be sitting outside, twiddling your thumbs and feeling rejected. So, if you get hit with this error, you need to give the server permission to access your key.

Methods for Fixing “SSH Permission Denied (publickey).”

  • Check SSH Agent

If you use an SSH agent to manage your keys, ensure your key is loaded into the agent. You can check the agent using the following command:

$ ssh-add -l

If the agent is not running, you can start it using the command:

$ eval "$(ssh-agent -s)"

  • Check the Key Permissions

Before checking the key permissions, ensure you have copied the public key to the remote server. If you have already done this, ensure the permissions on the key files are correct. The private key file should have 600 permissions, and the public key file should have 644 permissions. To change the file permissions, execute the following commands:

$ chmod 600 ~/.ssh/id_rsa

$ chmod 644 ~/.ssh/id_rsa.pub

  • Check SSH Configuration

You should check the SSH configuration files to ensure the server is configured to accept public key authentication. The following lines should be present in the SSH configuration file:

RSAAuthentication yes

PubkeyAuthentication yes

AuthorizedKeysFile .ssh/authorized_keys

If these lines are missing, add them to the configuration file and save the changes.

  • Check Server Logs

If none of the above methods works, you should check the server logs to discover the problem’s cause. The server logs are usually in the /var/log/auth.log or /var/log/secure file. You can view the logs using the following command:

$ tail -f /var/log/auth.log

Conclusion

The «SSH Permission Denied (publickey)» error is a common issue users face while using SSH. You can try several methods to resolve the issue, including checking the SSH agent, key permissions, SSH configuration, and server logs. Following these methods, you can quickly fix the «Permission Denied (publickey)» error and access your remote server.

  • The Permission Denied (publickey) error is common when trying to SSH into a server. It’s typically caused by the SSH server rejecting authentication attempts due to incorrect key configurations or a lack of permission to use them.
  • Various reasons, including expired or removed keys, incorrect file permissions, and server SSH configuration changes can cause the error message. This can make it challenging to pinpoint the exact cause.
  • To fix the error, you should first ensure that your keys are correctly configured on both the client and server, reset the permissions on the “authorized_keys” file, and check the server’s SSH configuration. You may also need to generate new keys and update your “authorized_keys” file on the server to resolve the issue.

People also read: 

  • How To Create An SSH Key 
  • SSH Connection Refused Error
  • Best SSH Client
  • How to Connect to SSH with Private Key

Понравилась статья? Поделить с друзьями:
  • Permission denied filezilla в чем ошибка
  • Perfusor compact s ошибка 046
  • Perfusor compact s ошибка 022
  • Performance loss ошибка рено премиум перевод
  • Performance loss ошибка рено премиум dxi