Permission denied publickey keyboard interactive windows

I tried to connect to planetlab node using ssh. It throws me error like Permission denied (publickey,keyboard-interactive). What does this mean? Here is the verbose of the exception. > OpenSSH_...

I tried to connect to planetlab node using ssh. It throws me error like Permission denied (publickey,keyboard-interactive). What does this mean?
Here is the verbose of the exception.

> OpenSSH_5.1p1 Debian-5ubuntu1, OpenSSL
> 0.9.8g 19 Oct 2007 debug1: Reading configuration data /etc/ssh/ssh_config
> debug1: Applying options for * debug2:
> ssh_connect: needpriv 0 debug1:
> Connecting to planetlab1.csee.usf.edu
> [131.247.2.241] port 22. debug1:
> Connection established. debug1:
> permanently_set_uid: 0/0 debug3: Not a
> RSA1 key file /home/keven/.ssh/id_rsa.
> debug2: key_type_from_name: unknown
> key type '-----BEGIN' debug3:
> key_read: missing keytype debug2:
> key_type_from_name: unknown key type
> 'Proc-Type:' debug3: key_read: missing
> keytype debug2: key_type_from_name:
> unknown key type 'DEK-Info:' debug3:
> key_read: missing keytype debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug3:
> key_read: missing whitespace debug2:
> key_type_from_name: unknown key type
> '-----END' debug3: key_read: missing
> keytype debug1: identity file
> /home/keven/.ssh/id_rsa type 1 debug1:
> Checking blacklist file
> /usr/share/ssh/blacklist.RSA-2048
> debug1: Checking blacklist file
> /etc/ssh/blacklist.RSA-2048 debug1:
> Remote protocol version 2.0, remote
> software version OpenSSH_4.7 debug1:
> match: OpenSSH_4.7 pat OpenSSH_4*
> debug1: Enabling compatibility mode
> for protocol 2.0 debug1: Local version
> string SSH-2.0-OpenSSH_5.1p1
> Debian-5ubuntu1 debug2: fd 3 setting
> O_NONBLOCK debug1: SSH2_MSG_KEXINIT
> sent debug1: SSH2_MSG_KEXINIT received
> debug2: kex_parse_kexinit:
> diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
> debug2: kex_parse_kexinit:
> ssh-rsa,ssh-dss debug2:
> kex_parse_kexinit:
> aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
> debug2: kex_parse_kexinit:
> aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
> debug2: kex_parse_kexinit:
> hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
> debug2: kex_parse_kexinit:
> hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
> debug2: kex_parse_kexinit:
> none,zlib@openssh.com,zlib debug2:
> kex_parse_kexinit:
> none,zlib@openssh.com,zlib debug2:
> kex_parse_kexinit:  debug2:
> kex_parse_kexinit:  debug2:
> kex_parse_kexinit: first_kex_follows 0
> debug2: kex_parse_kexinit: reserved 0 
> debug2: kex_parse_kexinit:
> diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
> debug2: kex_parse_kexinit:
> ssh-rsa,ssh-dss debug2:
> kex_parse_kexinit:
> aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
> debug2: kex_parse_kexinit:
> aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
> debug2: kex_parse_kexinit:
> hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
> debug2: kex_parse_kexinit:
> hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
> debug2: kex_parse_kexinit:
> none,zlib@openssh.com debug2:
> kex_parse_kexinit:
> none,zlib@openssh.com debug2:
> kex_parse_kexinit:  debug2:
> kex_parse_kexinit:  debug2:
> kex_parse_kexinit: first_kex_follows 0
> debug2: kex_parse_kexinit: reserved 0 
> debug2: mac_setup: found hmac-md5
> debug1: kex: server->client aes128-cbc
> hmac-md5 none debug2: mac_setup: found
> hmac-md5 debug1: kex: client->server
> aes128-cbc hmac-md5 none debug1:
> SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192)
> sent debug1: expecting
> SSH2_MSG_KEX_DH_GEX_GROUP debug2:
> dh_gen_key: priv key bits set: 128/256
> debug2: bits set: 508/1024 debug1:
> SSH2_MSG_KEX_DH_GEX_INIT sent debug1:
> expecting SSH2_MSG_KEX_DH_GEX_REPLY
> debug3: check_host_in_hostfile:
> filename /root/.ssh/known_hosts
> debug3: check_host_in_hostfile: match
> line 1 debug3: check_host_in_hostfile:
> filename /root/.ssh/known_hosts
> debug3: check_host_in_hostfile: match
> line 2 debug1: Host
> 'planetlab1.csee.usf.edu' is known and
> matches the RSA host key. debug1:
> Found key in /root/.ssh/known_hosts:1
> debug2: bits set: 535/1024 debug1:
> ssh_rsa_verify: signature correct
> debug2: kex_derive_keys debug2:
> set_newkeys: mode 1 debug1:
> SSH2_MSG_NEWKEYS sent debug1:
> expecting SSH2_MSG_NEWKEYS debug2:
> set_newkeys: mode 0 debug1:
> SSH2_MSG_NEWKEYS received debug1:
> SSH2_MSG_SERVICE_REQUEST sent debug2:
> service_accept: ssh-userauth debug1:
> SSH2_MSG_SERVICE_ACCEPT received
> debug2: key: /home/keven/.ssh/id_rsa
> (0xb80c9878) debug1: Authentications
> that can continue:
> publickey,keyboard-interactive debug3:
> start over, passed a different list
> publickey,keyboard-interactive debug3:
> preferred
> gssapi-keyex,gssapi-with-mic,gssapi,publickey,keyboard-interactive,password
> debug3: authmethod_lookup publickey
> debug3: remaining preferred:
> keyboard-interactive,password debug3:
> authmethod_is_enabled publickey
> debug1: Next authentication method:
> publickey debug1: Offering public key:
> /home/keven/.ssh/id_rsa debug3:
> send_pubkey_test debug2: we sent a
> publickey packet, wait for reply
> debug1: Authentications that can
> continue:
> publickey,keyboard-interactive debug2:
> we did not send a packet, disable
> method debug3: authmethod_lookup
> keyboard-interactive debug3: remaining
> preferred: password debug3:
> authmethod_is_enabled
> keyboard-interactive debug1: Next
> authentication method:
> keyboard-interactive debug2:
> userauth_kbdint debug2: we sent a
> keyboard-interactive packet, wait for
> reply debug1: Authentications that can
> continue:
> publickey,keyboard-interactive debug3:
> userauth_kbdint: disable: no
> info_req_seen debug2: we did not send
> a packet, disable method debug1: No
> more authentication methods to try.
> Permission denied
> (publickey,keyboard-interactive).

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.

    Settings icon in the user bar

  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.
    SSH key listing in GitHub

  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.

    Settings icon in the user bar

  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.
    SSH key listing in GitHub

  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.

    Settings icon in the user bar

  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.
    SSH key listing in GitHub

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

День добрый. Возник вопрос с авторизацией в 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: По той же ссылке добавлен и лог сервера с небольшим отличием — на текущий момент не было доступа к нужному устройству, поэтому ситуация продублирована в виртуальной машине.

I’m trying to build a git repo server with a windows remote. Here is my ssh server and local client building environment:

Server env
1. windows os
2. mysysgit installed
3. copssh installed
4. remote cloud server

client
1. centOS 7 on vmware
2. local pc

Here is my already taken actions.

1. generate a public-private key pair with ssh-keygen -t rsa on my centos client
2. add a git user named svccopssh in my remote windows server
3. copy my centos ~/.ssh/id_rsa.pub to the server folder d:/Users/svccopssh/.ssh, in which copssh reads public-ssh-key, and rename it as authorized_keys
4. run test:
ssh -vT svccopssh@remoteIP

The result comes out like this:

[is_january@localhost .ssh]$ ssh -vT svccopssh@120.76.123.231
OpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Connecting to 120.76.123.231 [120.76.123.231] port 22.
debug1: Connection established.
debug1: identity file /home/is_january/.ssh/id_rsa type 1
debug1: identity file /home/is_january/.ssh/id_rsa-cert type -1
debug1: identity file /home/is_january/.ssh/id_dsa type -1
debug1: identity file /home/is_january/.ssh/id_dsa-cert type -1
debug1: identity file /home/is_january/.ssh/id_ecdsa type -1
debug1: identity file /home/is_january/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/is_january/.ssh/id_ed25519 type -1
debug1: identity file /home/is_january/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.1
debug1: match: OpenSSH_7.1 pat OpenSSH* compat 0x04000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-sha1-etm@openssh.com none
debug1: kex: curve25519-sha256@libssh.org need=20 dh_need=20
debug1: kex: curve25519-sha256@libssh.org need=20 dh_need=20
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDS 26:95:35:2c:32:ad:46:14:94:5e:71:95:b7:f7:2d:aa
debug1: Host '120.76.123.231' is known and matches the ECDSA host key.
debug1: Found key in /home/is_january/.ssh/known_hosts:1
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/is_january/.ssh/id_rsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Trying private key: /home/is_january/.ssh/id_dsa
debug1: Trying private key: /home/is_january/.ssh/id_ecdsa
debug1: Trying private key: /home/is_january/.ssh/id_ed25519
debug1: Next authentication method: keyboard-interactive
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: No more authentication methods to try.
Permission denied (publickey,keyboard-interactive).

Any suggestions ? I am sure that the same public-key works well on github ssh-key

asked Sep 7, 2016 at 15:15

is_january's user avatar

is_januaryis_january

211 silver badge4 bronze badges

2

Well, actually, I’ve figured out what the problem is and solved it after all.

When I installed my copssh client, there was a step which asked me to choose user directory. I used my customized configuration, which was directory d:/Users/svccopssh/.ssh. However, the exact directory where svccopssh reads public-keys from is d:/copssh/home/svccopssh/.ssh, obviously not the directory I’ve used in my installation. After I changed my authorized_keys location to the right place: path/to/copssh_loaction/home/yourUserName/.ssh, it worked.

answered Sep 11, 2016 at 9:25

is_january's user avatar

is_januaryis_january

211 silver badge4 bronze badges

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.

  • Главная

  • Инструкции

  • 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 использует для проверки подлинности пользователей.

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.

Понравилась статья? Поделить с друзьями:
  • Performance options windows 11 где находится
  • Performance monitor не работает как исправить windows 7
  • Performance monitor users в русской windows
  • Perfom exe что это за процесс windows 10
  • Perfnet 2004 windows 10 как исправить