Ошибка отказа в разрешении (публичный ключ) при попытке подключиться к Google Cloud Shell через SSH

Я следую здесь документации Google Cloud Shell REST API, в которой показано использование users.environments.publicKeys.create метод добавления открытого ключа SSH в мой Cloud Shell.

Я использовал ssh-keygen для создания пары открытого / закрытого ключей и успешно добавил открытый ключ в свой Cloud Shell с помощью этого API. После этого я могу подтвердить, что открытый ключ доступен, используя users.environments.get, чтобы получить подробную информацию о моей оболочке, которая показывает этот открытый ключ.

Каждый раз, когда я пытаюсь подключиться к Cloud Shell по SSH с помощью соответствующего закрытого ключа, я получаю сообщение об ошибке Permission denied (publickey).

  • Я пробовал использовать ту же пару открытого и закрытого ключей для подключения к другим серверам, и она работает нормально, поэтому это исключит проблему с ключами.
  • Я пробовал подключиться с нескольких клиентов Windows и Linux, чтобы исключить какие-либо проблемы с разрешениями локальных файлов, но безуспешно.
  • Я пробовал несколько ключей, но получил тот же результат.

Вот результат моей попытки подключиться через SSH с машины Ubuntu:

ssh -i .ssh/id_rsa -p 6000 user@devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev -vvv

OpenSSH_7.2p2 Ubuntu-4ubuntu2.8, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev" port 6000
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev [xx.xx.xx.xx] port 6000.
debug1: Connection established.
debug1: identity file .ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file .ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u6
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u6 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev:6000 as 'user'
debug3: put_host_port: [devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev]:6000
debug3: hostkeys_foreach: reading file "/home/local_user/.ssh/known_hosts"
debug3: record_hostkey: found key type RSA in file /home/local_user/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from [devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev]:6000
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa,[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected],zlib
debug2: compression stoc: none,[email protected],zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256
debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: MACs ctos: hmac-md5,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: hmac-md5,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected]
debug2: compression stoc: none,[email protected]
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: [email protected]
debug1: kex: host key algorithm: rsa-sha2-512
debug1: kex: server->client cipher: [email protected] MAC: <implicit> compression: none
debug1: kex: client->server cipher: [email protected] MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ssh-rsa SHA256:oaU6VCSAN/xtJF6bMyDpuffYo6Cqsqsv44JsJ5Z/5/4
debug3: put_host_port: [xx.xx.xx.xx]:6000
debug3: put_host_port: [devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev]:6000
debug3: hostkeys_foreach: reading file "/home/local_user/.ssh/known_hosts"
debug3: record_hostkey: found key type RSA in file /home/local_user/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from [devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev]:6000
debug3: hostkeys_foreach: reading file "/home/local_user/.ssh/known_hosts"
debug3: record_hostkey: found key type RSA in file /home/local_user/.ssh/known_hosts:2
debug3: load_hostkeys: loaded 1 keys from [xx.xx.xx.xx]:6000
debug1: Host '[devshell-vm-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cloudshell.dev]:6000' is known and matches the RSA host key.
debug1: Found key in /home/local_user/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug2: key: .ssh/id_rsa (0x56066a887910), explicit
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,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 RSA public key: .ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

РЕДАКТИРОВАТЬ: результат sudo grep -i ssh /var/log/auth.log запуска из моей облачной оболочки:

sshd[569]: rexec line 33: Deprecated option KeyRegenerationInterval
sshd[569]: rexec line 34: Deprecated option ServerKeyBits
sshd[569]: rexec line 45: Deprecated option RSAAuthentication
sshd[569]: rexec line 52: Deprecated option RhostsRSAAuthentication
sshd[569]: reprocess config line 45: Deprecated option RSAAuthentication sshd[569]: reprocess config line 52: Deprecated option RhostsRSAAuthentication sshd[569]: error: Received disconnect from xx.xx.xx.xx port 54590:14: No supported authentication methods available [preauth]
sshd[569]: Disconnected from xx.xx.xx.xx port 54590 [preauth
  • Я убедился, что закрытый ключ не поврежден
  • Я подтвердил, что имя пользователя, с которым я подключаюсь, совпадает с тем, которое ожидает облачная оболочка.
  • Я убедился, что файл authorized_keys в системе Cloud Shell имеет разрешения «rw-r-r» (результат -rw-r--r-- 1 root root 2584 Aug 26 12:08 /etc/ssh/keys/authorized_keys)

person Jason Dark    schedule 25.08.2019    source источник


Ответы (1)


[ОБНОВИТЬ]

Выполните следующие команды, которые используют alpha SDK для создания / установки ключа SSH:

gcloud components install alpha
gcloud alpha cloud-shell ssh --dry-run

Затем вы можете использовать файл ключей SSH ~/.ssh/google_compute_engine.

Если это сработает, значит проблема в вашем SSH-ключах.

[КОНЕЦ ОБНОВЛЕНИЯ]

В выходных данных отладки строки 87 и 88:

debug3: send packet: type 50
debug3: receive packet: type 51

Строка 87 означает «запрос авторизации пользователя». Строка 88 означает «сбой аутентификации пользователя».

Сервер SSH отклонил ваш ключ SSH.

Выполните эту команду в Cloud Shell, чтобы просмотреть журнал для SSHD. Вы должны увидеть точную ошибку, почему ваш ключ SSH был отклонен:

sudo grep -i ssh /var/log/auth.log

Возможные проблемы / решения:

  • Поврежденный закрытый ключ в вашей локальной системе.
  • Закрытый ключ не совпадает с открытым ключом удаленной системы в authorized_keys.
  • Имя пользователя «пользователь» не соответствует удаленной системе.
  • Неверные права доступа к файлам в удаленной системе authorized_keys (должно быть 0644 - "rw-r-r")
  • Сервер OpenSSH не может прочитать authorized_keys (отсутствует разрешение на чтение файла).

Примечание. Убедитесь, что ваш закрытый ключ (.ssh / id_rsa) доступен для чтения только вам (нет прав на запись для кого-либо, нет прав на чтение для кого-либо, кроме вас) - 0400.

person John Hanley    schedule 25.08.2019
comment
Спасибо за предложения: это журналы, которые создаются, когда я пытаюсь подключиться: - person Jason Dark; 26.08.2019
comment
sshd [569]: rexec строка 33: устаревшая опция KeyRegenerationInterval sshd [569]: rexec строка 34: устаревшая опция ServerKeyBits sshd [569]: rexec строка 45: устаревшая опция RSAAuthentication sshd [569]: rexecshdathentication option [569]: повторная проверка RSAuthentication, строка 52: отказ от аутентификации. 569]: строка конфигурации повторной обработки 45: Устаревшая опция RSAAuthentication sshd [569]: строка конфигурации повторной обработки 52: Устаревшая опция RhostsRSAAuthentication sshd [569]: ошибка: Получено отключение от порта xx.xx.xx.xx 54590: 14: Нет поддерживаемых методов аутентификации доступно [preauth] hd [569]: отключено от порта xx.xx.xx.xx 54590 [preauth] - person Jason Dark; 26.08.2019
comment
1) Пожалуйста, не публикуйте детали в комментариях. Мало кто попытается их прочитать. Отредактируйте свой вопрос, отформатируйте новую информацию, чтобы мы могли ее легко прочитать, а затем оставьте комментарий, что вопрос был обновлен. 2) Я дал вам список возможных проблем. Опубликуйте детали после проверки каждой возможной проблемы. 3) Еще раз проверьте файл журнала. Есть ли строчка с упоминанием публичного ключа? 4) Если в файле журнала Cloud Shell нет сообщения об ошибке, возможно, проблема заключается в том, что каталог ~/.ssh имеет неправильные права доступа к файлу или ~/.ssh/id_rsa имеет неправильные права доступа к файлу. - person John Hanley; 26.08.2019
comment
Спасибо за указатели. Я обновил главный вопрос. В моих журналах подключений я вижу debug1: key_load_public: нет такого файла или каталога, что заставляет меня думать, что это может быть проблема с правами доступа к файлу. Посмотрю и обновлю. - person Jason Dark; 26.08.2019
comment
1) key_load_public - это просто предупреждение о том, что файл открытого ключа не существует. Это не требуется для аутентификации, поскольку будет использоваться закрытый ключ. 2) Я сомневаюсь, что в Cloud Shell есть пользователь с именем user. Имя пользователя определяется идентификаторами Google Cloud IAM (учетными записями участников), если вы просто не маскируете настоящее имя пользователя. 3) Запустите Cloud Shell. В окне терминала выполните gcloud auth list. Это ваша личность пользователя. - person John Hanley; 26.08.2019
comment
Я не подключаюсь к пользователю с именем пользователя, я использую правильное имя пользователя. Я просто запутал это для своего публичного сообщения. В gcloud auth list я вижу свой адрес электронной почты как пользователь. - person Jason Dark; 26.08.2019
comment
Если вы понимаете язык Go, я написал программу, которая подключается к Cloud Shell и поддерживает SSH и SCP. Это покажет вам подробную информацию о подключении к Cloud Shell. В коде также показано, как запустить программу ssh при подключении к Cloud Shell с правильными параметрами, ключами и т. Д. github.com/jhanley-com/google-cloud-shell-cli-go - person John Hanley; 26.08.2019