Não foi possível obter permissão SSH com chave pública negada

Não foi possível obter permissão SSH com chave pública negada

Vou tentar resumir isso da melhor maneira possível e com o máximo de detalhes possível. Implantei meu primeiro site Django em um servidor Ubuntu (23.04) em Linode ontem à noite depois de seguir este Corey Schafer Python Djangotutorial. Tudo correu bem e eu configurei o SSH conforme o tutorial é apresentado no vídeo, cerca de 23 a 25 minutos sem problemas. Eu verifiquei que tudo estava funcionando em um ponto. Saí do servidor e verifiquei que poderia voltar via SSH sem nenhum problema. Continuando, passei mais uma ou duas horas configurando um monte de outras coisas e certificando-me de que o site estava ativo antes de ir para a cama e sair do servidor. Hoje volto para me conectar ao servidor e recebo uma mensagemPermission denied (publickey).

Sabendo que adicionei um firewall depois de tudo isso, achei ótimo, provavelmente me bloqueei de conexões ssh ou algo assim. No entanto, depois de pesquisar no Google, encontrei esse modificador ssh -vT user@IPe rapidamente vi que, de fato, ele parece estar tentando se conectar por ssh e uma conexão é feita, mas está falhando por motivos que não entendo completamente.

Em seguida, tentei fazer login como usuário root via Linodes Weblish e consegui entrar e tentei verificar algumas coisas.

• Primeiro verifiquei que existe uma pasta no local /home/user/.sshque contém um arquivo com a chave.

• Em segundo lugar, verifiquei as permissões voltando ao vídeo passo a passo para a pasta ~/.ssh/ e o conteúdo e executei os dois comandos a seguir novamente. sudo chmod 700 ~/.ssh/esudo chmod 600 ~/.ssh/*

O resultado é o seguinte para a pasta ssh em meu diretório pessoal.

lewpiper@django-server:~$ la -la
total 40
drwxrwxrwx 6 lewpiper lewpiper 4096 Jun 14 06:37 .
drwxr-xr-x 3 root     root     4096 Jun 14 05:22 ..
-rw------- 1 lewpiper lewpiper  100 Jun 14 05:34 .bash_history
-rw-r--r-- 1 lewpiper lewpiper  220 Jun 14 05:22 .bash_logout
-rw-r--r-- 1 lewpiper lewpiper 3771 Jun 14 05:22 .bashrc
drwx------ 4 lewpiper lewpiper 4096 Jun 14 06:09 .cache
drwxrwxr-x 3 lewpiper lewpiper 4096 Jun 14 06:37 .local
drwxr-xr-x 8 lewpiper www-data 4096 Jun 14 06:36 Portfolio
-rw-r--r-- 1 lewpiper lewpiper  807 Jun 14 05:22 .profile
drwx------ 2 lewpiper lewpiper 4096 Jun 15 06:03 .ssh
-rw-r--r-- 1 lewpiper lewpiper    0 Jun 14 05:33 .sudo_as_admin_successful

A seguir estão as permissões para o arquivo dentro da pasta ssh no diretório inicial.

lewpiper@django-server:~/.ssh$ ls -la
total 12
drwx------ 2 lewpiper lewpiper 4096 Jun 15 06:03 .
drwxrwxrwx 6 lewpiper lewpiper 4096 Jun 14 06:37 ..
-rw------- 1 lewpiper lewpiper  749 Jun 14 05:32 authorized_keys

• Terceiro eu configurei um firewall no servidor e os tipos de conexão permitidos atualmente são os seguintes.

lewpiper@django-server:~$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere                  
80/tcp                     ALLOW       Anywhere                  
22/tcp (v6)                ALLOW       Anywhere (v6)             
80/tcp (v6)                ALLOW       Anywhere (v6)  

• Finalmente fui até o /etc/ssh/sshd_configarquivo e por enquanto ativei o PasswordAuthentication novamente até poder chegar ao fundo do problema do ssh. Então, por enquanto, posso fazer login sem ter que usar as ofertas weblish do Linode. Porém, depois de fazer isso, tentei reiniciar o serviço ssh no servidor usando o seguinte comando, sudo systemctl restart sshdconforme o tutorial diz que você deve fazer ao editar este arquivo. Em vez disso, recebi um erro. Failed to restart sshd.service: Unit sshd.service not found.Lembro-me de ter recebido esta mensagem ontem à noite também quando estava fazendo a configuração do servidor e uma rápida pesquisa no Google descobriu que o nome do serviço mudou e então tentei sudo systemctl restart sshe isso pareceu funcionar ontem à noite, mas Eu me pergunto se eu estava incorreto nisso.

Abaixo está o arquivo sshd_config como o tenho agora, mas observe que alterei a autenticação da senha para sim para poder fazer login sem ter que usar a chave rsa gerada, que é o meu problema.

LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

Questões: Portanto, minha pergunta daqui tem duas partes. Perdi alguma coisa que pudesse fazer para solucionar melhor por que isso está acontecendo ou poderia tentar? Dois, se não houver outra solução de problemas recomendada, devo apenas tentar excluir meu arquivo autorizado_keys no servidor e copiá-lo com segurança para o servidor? Observe que nem tenho certeza se isso funcionaria, porque não estou convencido de que esse seja o problema. Meu palpite é que pode estar faltando alguma coisa ou há mais coisas nas Failed to restart sshd.service: Unit sshd.service not found.mensagens que mencionei anteriormente. Também existe alguma ideia de apenas reiniciar o servidor? Parece estranho, mas talvez algo como o firewall ou algo assim seja recarregado e tudo fique feliz.

informação relacionada