Openssh server refused our key windows

I created key pair using puttygen.exe (client is windows 8). On server (Ubuntu 12.04.3 LTS), I have put my public key in ~/.ssh/authorized_keys. The public key is this: ssh-rsa

Running Windows 8.1 I ran into the server refused our key problem.

Following the guide: https://winscp.net/eng/docs/guide_windows_openssh_server
It was easy to make a connection using the Windows login username and password. However, authenticating with the username in combination with a private key, the response was server refused our key.

Getting it to work with a public key came down to the permissions on the file:
C:ProgramDatasshadministrators_authorized_keys

This is a helpful page: https://github.com/PowerShell/Win32-OpenSSH/wiki/Troubleshooting-Steps

Stop the two OpenSSH services, then open a command prompt with admin permissions. Then run:
C:OpenSSH-Win32>c:OpenSSH-Win32sshd.exe -ddd

Note: specify the full path to the exe otherwise sshd complains.
This creates a one-time use connection listener. The -ddd is verbose level 3.

After making a connection, scanning the logs revealed:

debug1: trying public key file __PROGRAMDATA__/ssh/administrators_authorized_keys
debug3: Failed to open file:C:/ProgramData/ssh/administrators_authorized_keys error:2
debug1: Could not open authorized keys '__PROGRAMDATA__/ssh/administrators_authorized_keys':
        No such file or directory

Had to create the file: C:ProgramDatasshadministrators_authorized_keys
And copy the public key text into it, e.g: ssh-rsa AAAA................MmpfXUCj rsa-key-20190505
And then save the file. I saved the file as UTF-8 with the BOM. Didn’t test ANSI.

Then running the one-time command line again, in the logs showed:

debug1: trying public key file __PROGRAMDATA__/ssh/administrators_authorized_keys
debug3: Bad permissions. Try removing permissions for user: S-1-5-11 on file C:/ProgramData/ssh/administrators_authorized_keys.
        Authentication refused.

S-1-5-11 is the name given to the System.

To fix the Bad permissions, right click on the administrators_authorized_keys file, goto the Security Tab , click the Advanced button and remove inherited permissions.
Then delete all Group or user names: except for the Windows login username, e.g: YourMachineNameusername
The permissions for that username should be Read Allow, Write Deny everything else is unchecked. The owner of the file should also be YourMachineNameusername

This fixed the problem.

Other Useful links:

Download OpenSSH-Win32.zip from: https://github.com/PowerShell/Win32-OpenSSH/releases

C# example of how to use the WinSCPnet.dll to make a connection to the OpenSSH server: https://winscp.net/eng/docs/library#csharp

Here is the code snippet to make a connection using the WinSCPnet.dll:

static void WinSCPTest() {
    SessionOptions ops = new SessionOptions {
        Protocol = Protocol.Sftp, 
        PortNumber = 22,
        HostName = "192.168.1.188", 
        UserName = "user123",
        //Password = "Password1",
        SshHostKeyFingerprint = @"ssh-rsa 2048 qu0f........................ddowUUXA="
    };

    ops.SshPrivateKeyPath = @"C:temprsa-key-20190505.ppk";

    using (Session session = new Session()) {
        session.Open(ops);
        MessageBox.Show("success");
    }
}

Replace SshHostKeyFingerprint and SshPrivateKeyPath with your own values.

Edit: added screenshot of administrators_authorized_keys file permissions:
enter image description here

When OpenSSH SSH Server is running as a Service, then only System should have permission. However, if running sshd.exe from the command prompt, then the current user should be the only one listed (read allow, write deny).

I’m attempting to use PuTTY to securely connect my remote desktop from my laptop to my desktop computer, and so far I have been successful in tunneling through the proper ports WITHOUT A KEY, just by using my username and password. These are both Windows machines, running Windows 10.

I generated a key using PuTTYGen, and each time I would copy and paste the public key into C:UsersChris.sshauthorized_keys (on the server) like so:

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQBl8kTxv8cxW5tSvNjId+qrype1ZA+zEO3Qag+BHhlMvvtrx/faZp8XMXbSqulZVqXNFnN0ADAaAv2hMltP+rft4R8X9qaJSIlYdPo8F3BmV5G2mu+AQKnOrGooLfwc2oa4qOfHJMqzciFqVVTAOjo3BQ3ZtZnN23os1WfiRCcwlNZgrRlgpUPkA/CgaWTDnlDpxvNZp3fVia8pDvLlqVIIn+Fu7UEJi/pNDUiexrky7nR0JzIL3ZAPAu6U26WLJA7fYw7nlySzz/BuxiPyIzeRT+qiHQuwf2yOkCXNIeQQjgLsbw0eS67TWC7pa6NbLa0KqmgDChdSNsSB5aKTMh3T rsa-key-20190410

Then, on the client, I select the private key file in Settings > Connection > SSH > Auth > Private key file for Authentication > C:UsersChrisDesktopSSH-KEYkey1.ppk

I have double and triple checked: the public key that I pasted into authorized_keys corresponds to the private key that is loaded into PuTTY.

When I attempt to connect the session, I get this error:

Using username "Chris".
Server refused our key
Chris@my.pub.lic.ip's password:

I am able to find no further documentation or error codes.

There is no log file present, but when I enabled logging manually and opened it up after connection, this was present in the file for the client:

Using username "Chris".
Server refused our key
Chris@my.pub.lic.ip's password:

I have tried both using Chris and chris, in addition to generating and using key pairs generated from the server, and from the client.

I later found an additional log file for the server in C:ProgramDatasshlogssshd.log:

1184 2019-04-10 12:38:48.995 Server listening on :: port 22.
1184 2019-04-10 12:38:48.995 Server listening on 0.0.0.0 port 22.
13568 2019-04-10 12:39:00.943 Authentication refused.
13568 2019-04-10 12:39:04.395 Connection closed by authenticating user chris my.pub.lic.ip port 54460 [preauth]

I’ve seen several suggestions about using chmod, and checking /var/log/secure, both of which are useless to me as they are linux commands and directories, and both of these machines are Windows.

I’ll admit: I’ve kind of been losing my marbles over this. I’m doing everything that every tutorial anywhere suggests, and nothing is working.

Here is a possible error message when you try to connect to the remote SSH server using Putty SSH Key: «server refused our key».

PuTTY Server Refused Our Key

This is because you haven’t copied your public key to the remote server or haven’t done it properly.

Your public key should exist in the authorized_keys file of the user account you used to login to the remote server. The solution is to copy the public key from your Windows 10 PC to the user’s authorized_keys file.

Note that each user has their own authorized_keys file in the home directory. For example, If you log in as user root, you need to place the public key to the «/root/.ssh/authorized_keys».

To solve the «server refused our key» error, you can do the following steps:

Open PuTTYgen, Go to File > Load Private key and open your Private Key File.

Open PuTTYgen, Go to File > Load Private key and open your Private Key File.

Highlight the Public key that was created in the text box and copy it to the clipboard.

server refused our key putty windows

Next, Log in to the Linux server and change to the home directory with the cd command:

cd ~/

Then, create the .ssh folder and the .ssh/authorized_keys file (if it doesn’t already exist):

mkdir ~/.ssh
touch ~/.ssh/authorized_keys

Open the authorized_keys file and paste the public key.

putty server refused our key

When you are finished, save the file exit the session.

To connect to the remote server. Open the PuTTY terminal and provide the IP address of the remote server. Then, Go to Connection > SSH > Auth and Load the private key after clicking on the Browse button.

Go to Connection > SSH > Auth and Load the private key after clicking on the Browse button

Click on Open to establish SSH connection to the Linux server. You should be able to connect to the server without getting «Server refused our key» error.

Errors are prevalent on the internet. When surfing, you would have encountered a lot of errors attempting to limit your productivity. Some computer faults are more targeted than others, and some are so precise that they only impact specific Internet browsers and not others.

As part of our Managed Cloud Services, we recently received this response from one of our customers. When utilising SSH keys to access the server, server owners frequently see this issue. This issue can be caused by various factors, including incorrect SSH key format, incorrect SSH key permissions, and more.

If you find yourself in this situation, read our comprehensive guide, which outlines several ways for swiftly and successfully resolving “Server Refused Our Key.” One of these will fix the problem, allowing you to return to your favourite website as quickly as possible.

If you want to see products that are similar, you can take a look at this one:

What Is “Server Refused Our Key”?

The account of the user who attempted to access the instance was either deleted or locked. The instance’s permissions are incorrect, or a directory is missing. When connecting to your AWS instance, you’re using the wrong private key file.

The use of a key to access the server is a safe method of doing so. The public key is stored on Vultr, while the private key is kept on the user’s computer. On the Vultr instance, the error “Server refused our key” clearly indicates that the server rejected the SSH key given for login.

What Causes “Server Refused Our Key”?

There are several causes behind it.

SSH server login, for example, necessitates stringent permissions for the critical files used. SSH refuses to authenticate if the user does not have the required privileges to read the SSH keys. The error server refused our key’ may also occur if any of the files in the. Ssh folder can be written by other users.

Another common cause of this problem is the usage of the incorrect public key format by the customer. This frequently occurs when users create an SSH key on Windows and copy it to Linux using puttygen. Because Windows divides the public key into numerous lines, this occurs.

This error can also be caused by issues with the SSH configuration file. Users have added SSH keys to their Vultr instances in the past. However, in the SSH configuration file, public key authentication was not enabled. As a result, users’ Vultr instances display the error server refused our key.’

How to Fix the “Server Refused Our Key”

Now let’s get down with our main event and learn about how you can fix the problems. Use the simple steps below.

If you want to see related products, we suggest checking this one out:

Step 1: Fix “Wrong permissions of SSH key”

To begin, double-check that the public key is correctly stored in the user’s home directory’s. Ssh folder and that proper ownership are assigned to these files.

Also, double-check that the SSH critical files’ rights and ownership are accurate. In other words, we make sure that the. Ssh folder and its parent folder have rights of 700, and this restricts the user’s access to the folder to only write permissions.

Similarly, on the client-side, ensure the private key’s permissions are set to 600 or more limited rights. We also ensure that the public key file in. ssh/authorised keys has permission 600, preventing other users from writing the key.

If you want to see similar products, you can check this one out:

Step 2: Fix “Wrong SSH key format”

Our Support Engineers validate how clients create SSH keys for the user in this section. We also examine the public key format and make any necessary changes. For example, we use the command below to convert the public key to a format that the OpenSSH server can understand. Furthermore, we validate that the SSH keys are all on a single line and have no leading or trailing spaces.

Step 3: Fix “SSH configuration issues”

Our Support Engineers activate public key authentication in the /etc/ssh/ssh config SSH configuration file in these circumstances. For example, to enable key-based authentication, we add the following line.

In addition, we make sure that the necessary file’s location is enabled. Each user’s authorised keys file is located in their home directory. For example, if you log in as root, you must add the public key to “/root/.ssh/authorised keys.”

To make these modifications take effect, we must restart the SSH service on the Vultr instance.

If you’re looking for other products that might interest you, here’s one to check out:

FAQ

Why does my server refuse my key?

The account of the person who attempted to access the instance was either locked or erased from the server. There are permissions issues on the instance, or a directory is missing. When connecting to your EC2 instance, you’re using the wrong private key file.

How do I fix the PuTTY server that refused my key?

  • generate a key pair with puttygen.exe (length: 1024 bits)
  • load the private key in the PuTTY profile.
  • enter the public key in
  • chmod 700
  • chmod 600
  • chown $USER:$USER.
  • change /etc/ssh/sshd_config so it contains AuthorizedKeysFile %h/
  • sudo service ssh restart.

How do I get my AWS private key?

One of the methods listed below can be used to produce a key pair. Go to https://console.aws.amazon.com/ec2/ to access the Amazon EC2 console. Select Key Pairs from the Network & Security menu in the navigation pane. Select the option to create a key pair.

Is SSL Free on AWS?

AWS Certificate Manager may provide free public SSL/TLS certificates. You just have to pay for the AWS resources you use to run your app.

If you’re looking for similar products, this one might be a good option for you:

Closing Words

One of the techniques listed above should have resolved the issue if you get the “Server Refused Our Key”. This problem is readily solved by using the strategies mentioned in this article.

Suppose you continue getting this problem when visiting the same page. In that case, it’s conceivable that the answer is in one of these approaches. You may be unfamiliar with the technologies involved. However, if you simply follow the instructions, one of these solutions should work for you.
The “Server Refused Our Key” message is quite common. The techniques for resolving it listed above have all been utilised successfully depending on the cause of the error.

I’m trying to setup ssh authentication with key files in stead of username/password. The client is a Windows box running PuTTY and the server is a Ubuntu 12.04 LTS server.

I downloaded puttygen.exe and had it generate a key pair. In /etc/ssh/sshd_config I have this line:

AuthorizedKeysFile %h/.ssh/authorized_keys

and on my client’s public key file it says this:

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "my@email.address.com"
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAr3Qo6T5XU06ZigGOd3eKvfBhFLhg5kWv8lz6
qJ2G9XCbexlPQGanPhh+vcPkhor6+7OmB+WSdHeNO652kTofnauTKcTCbHjsT7cJ
GNrO8WVURRh4fabknUHPmauerWQZ6TgRPGaz0aucU+2C+DUo2SKVFDir1vb+4u83
AV1pKxs=my@email.address.com
---- END SSH2 PUBLIC KEY ----

I copied the part from «ssh-rsa AAA» to «my@email.address.com» and put that in the file ~/.ssh/authorized_keys on my server (in my own homefolder). In PuTTY under Connection > SSH > Auth I entered the path to the private key it generated on my client and saved the session settings.

I restarted the ssh server with

sudo service ssh restart

Now if I load the profile in PuTTY (I verified the private key is still in Connection > SSH > Auth and that the path is correct) and run the profile, it says

Server refused our key

I tried putting the public key in a file under the directory ./ssh/authorized_keys/ but that didn’t help so I used ./ssh/authorized_keys as a file, pasting the key in it. I also tried generating a private/public key pair on the server, putting the public key in ./ssh/authorized_files and loading the private one in PuTTY on my client. Rebooting the server didn’t help either.

I found that the error may be solved by putting the key in a place outside the user’s home folder but that’s only useful if the home folder is encrypted, which this one is not.

Also tried generating a 4096 bit key, thinking perhaps 1024 was too short.

How can I get this to work? Thanks!

EDIT:

Ok, /var/log/auth.log said:

sshd: Authentication refused: bad ownership or modes for directory /home/vorkbaard/.ssh

Google tells me ~/.ssh/ should be 700 and and ~/.ssh/authorized_keys should be 600, so I did that. Now /var/log/auth.log says:

sshd: error: key_read: uudecode AAAAB3N [etc etc etc until about 3/4 of my public key]

предыдущая глава | содержание | следующая глава

  • 10.1 «The server’s host key is not cached in the registry»
  • 10.2 «WARNING — POTENTIAL SECURITY BREACH!»
  • 10.3 «SSH protocol version 2 required by our configuration but remote only provides (old, insecure) SSH-1»
  • 10.4 «The first cipher supported by the server is … below the configured warning threshold»
  • 10.5 «Remote side sent disconnect message type 2 (protocol error): «Too many authentication failures for root»»
  • 10.6 «Out of memory»
  • 10.7 «Internal error», «Internal fault», «Assertion failed»
  • 10.8 «Unable to use key file», «Couldn’t load private key», «Couldn’t load this key»
  • 10.9 «Server refused our key», «Server refused our public key», «Key refused»
  • 10.10 «Access denied», «Authentication refused»
  • 10.11 «No supported authentication methods available»
  • 10.12 «Incorrect MAC received on packet» or «Incorrect CRC received on packet»
  • 10.13 «Incoming packet was garbled on decryption»
  • 10.14 «PuTTY X11 proxy: various errors»
  • 10.15 «Network error: Software caused connection abort»
  • 10.16 «Network error: Connection reset by peer»
  • 10.17 «Network error: Connection refused»
  • 10.18 «Network error: Connection timed out»
  • 10.19 «Network error: Cannot assign requested address»

This chapter lists a number of common error messages which PuTTY and its associated tools can produce, and explains what they mean in more detail.

We do not attempt to list all error messages here: there are many which should never occur, and some which should be self-explanatory. If you get an error message which is not listed in this chapter and which you don’t understand, report it to us as a bug (see appendix B) and we will add documentation for it.

10.1 «The server’s host key is not cached in the registry»

This error message occurs when PuTTY connects to a new SSH server. Every server identifies itself by means of a host key; once PuTTY knows the host key for a server, it will be able to detect if a malicious attacker redirects your connection to another machine.

If you see this message, it means that PuTTY has not seen this host key before, and has no way of knowing whether it is correct or not. You should attempt to verify the host key by other means, such as asking the machine’s administrator.

If you see this message and you know that your installation of PuTTY has connected to the same server before, it may have been recently upgraded to SSH protocol version 2. SSH protocols 1 and 2 use separate host keys, so when you first use SSH-2 with a server you have only used SSH-1 with before, you will see this message again. You should verify the correctness of the key as before.

See section 2.2 for more information on host keys.

10.2 «WARNING — POTENTIAL SECURITY BREACH!»

This message, followed by «The server’s host key does not match the one PuTTY has cached in the registry», means that PuTTY has connected to the SSH server before, knows what its host key should be, but has found a different one.

This may mean that a malicious attacker has replaced your server with a different one, or has redirected your network connection to their own machine. On the other hand, it may simply mean that the administrator of your server has accidentally changed the key while upgrading the SSH software; this shouldn’t happen but it is unfortunately possible.

You should contact your server’s administrator and see whether they expect the host key to have changed. If so, verify the new host key in the same way as you would if it was new.

See section 2.2 for more information on host keys.

10.3 «SSH protocol version 2 required by our configuration but remote only provides (old, insecure) SSH-1»

By default, PuTTY only supports connecting to SSH servers that implement SSH protocol version 2. If you see this message, the server you’re trying to connect to only supports the older SSH-1 protocol.

If the server genuinely only supports SSH-1, then you need to either change the «SSH protocol version» setting (see section 4.19.4), or use the -1 command-line option; in any case, you should not treat the resulting connection as secure.

You might start seeing this message with new versions of PuTTY (from 0.68 onwards) where you didn’t before, because it used to be possible to configure PuTTY to automatically fall back from SSH-2 to SSH-1. This is no longer supported, to prevent the possibility of a downgrade attack.

10.4 «The first cipher supported by the server is … below the configured warning threshold»

This occurs when the SSH server does not offer any ciphers which you have configured PuTTY to consider strong enough. By default, PuTTY puts up this warning only for Blowfish, single-DES, and Arcfour encryption.

See section 4.22 for more information on this message.

(There are similar messages for other cryptographic primitives, such as host key algorithms.)

10.5 «Remote side sent disconnect message type 2 (protocol error): «Too many authentication failures for root»»

This message is produced by an OpenSSH (or Sun SSH) server if it receives more failed authentication attempts than it is willing to tolerate.

This can easily happen if you are using Pageant and have a large number of keys loaded into it, since these servers count each offer of a public key as an authentication attempt. This can be worked around by specifying the key that’s required for the authentication in the PuTTY configuration (see section 4.23.8); PuTTY will ignore any other keys Pageant may have, but will ask Pageant to do the authentication, so that you don’t have to type your passphrase.

On the server, this can be worked around by disabling public-key authentication or (for Sun SSH only) by increasing MaxAuthTries in sshd_config.

10.6 «Out of memory»

This occurs when PuTTY tries to allocate more memory than the system can give it. This may happen for genuine reasons: if the computer really has run out of memory, or if you have configured an extremely large number of lines of scrollback in your terminal. PuTTY is not able to recover from running out of memory; it will terminate immediately after giving this error.

However, this error can also occur when memory is not running out at all, because PuTTY receives data in the wrong format. In SSH-2 and also in SFTP, the server sends the length of each message before the message itself; so PuTTY will receive the length, try to allocate space for the message, and then receive the rest of the message. If the length PuTTY receives is garbage, it will try to allocate a ridiculous amount of memory, and will terminate with an «Out of memory» error.

This can happen in SSH-2, if PuTTY and the server have not enabled encryption in the same way (see question A.7.3 in the FAQ).

This can also happen in PSCP or PSFTP, if your login scripts on the server generate output: the client program will be expecting an SFTP message starting with a length, and if it receives some text from your login scripts instead it will try to interpret them as a message length. See question A.7.4 for details of this.

10.7 «Internal error», «Internal fault», «Assertion failed»

Any error beginning with the word «Internal» should never occur. If it does, there is a bug in PuTTY by definition; please see appendix B and report it to us.

Similarly, any error message starting with «Assertion failed» is a bug in PuTTY. Please report it to us, and include the exact text from the error message box.

10.8 «Unable to use key file», «Couldn’t load private key», «Couldn’t load this key»

Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication, or given by Pageant when trying to load a private key.

If you see one of these messages, it often indicates that you’ve tried to load a key of an inappropriate type into PuTTY, Plink, PSCP, PSFTP, or Pageant.

You may have tried to load an SSH-2 key in a «foreign» format (OpenSSH or ssh.com) directly into one of the PuTTY tools, in which case you need to import it into PuTTY’s native format (*.PPK) using PuTTYgen – see section 8.2.12.

Alternatively, you may have specified a key that’s inappropriate for the connection you’re making. The SSH-2 and the old SSH-1 protocols require different private key formats, and a SSH-1 key can’t be used for a SSH-2 connection (or vice versa).

10.9 «Server refused our key», «Server refused our public key», «Key refused»

Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication.

If you see one of these messages, it means that PuTTY has sent a public key to the server and offered to authenticate with it, and the server has refused to accept authentication. This usually means that the server is not configured to accept this key to authenticate this user.

This is almost certainly not a problem with PuTTY. If you see this type of message, the first thing you should do is check your server configuration carefully. Common errors include having the wrong permissions or ownership set on the public key or the user’s home directory on the server. Also, read the PuTTY Event Log; the server may have sent diagnostic messages explaining exactly what problem it had with your setup.

Section 8.3 has some hints on server-side public key setup.

10.10 «Access denied», «Authentication refused»

Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) during authentication.

If you see one of these messages, it means that the server has refused all the forms of authentication PuTTY has tried and it has no further ideas.

It may be worth checking the Event Log for diagnostic messages from the server giving more detail.

This error can be caused by buggy SSH-1 servers that fail to cope with the various strategies we use for camouflaging passwords in transit. Upgrade your server, or use the workarounds described in section 4.28.11 and possibly section 4.28.12.

10.11 «No supported authentication methods available»

This error indicates that PuTTY has run out of ways to authenticate you to an SSH server. This may be because PuTTY has TIS or keyboard-interactive authentication disabled, in which case see section 4.23.4 and section 4.23.5.

10.12 «Incorrect MAC received on packet» or «Incorrect CRC received on packet»

This error occurs when PuTTY decrypts an SSH packet and its checksum is not correct. This probably means something has gone wrong in the encryption or decryption process. It’s difficult to tell from this error message whether the problem is in the client, in the server, or in between.

In particular, if the network is corrupting data at the TCP level, it may only be obvious with cryptographic protocols such as SSH, which explicitly check the integrity of the transferred data and complain loudly if the checks fail. Corruption of protocols without integrity protection (such as HTTP) will manifest in more subtle failures (such as misdisplayed text or images in a web browser) which may not be noticed.

Occasionally this has been caused by server bugs. An example is the bug described at section 4.28.8, although you’re very unlikely to encounter that one these days.

In this context MAC stands for Message Authentication Code. It’s a cryptographic term, and it has nothing at all to do with Ethernet MAC (Media Access Control) addresses, or with the Apple computer.

10.13 «Incoming packet was garbled on decryption»

This error occurs when PuTTY decrypts an SSH packet and the decrypted data makes no sense. This probably means something has gone wrong in the encryption or decryption process. It’s difficult to tell from this error message whether the problem is in the client, in the server, or in between.

If you get this error, one thing you could try would be to fiddle with the setting of «Miscomputes SSH-2 encryption keys» (see section 4.28.10) or «Ignores SSH-2 maximum packet size» (see section 4.28.5) on the Bugs panel.

10.14 «PuTTY X11 proxy: various errors»

This family of errors are reported when PuTTY is doing X forwarding. They are sent back to the X application running on the SSH server, which will usually report the error to the user.

When PuTTY enables X forwarding (see section 3.4) it creates a virtual X display running on the SSH server. This display requires authentication to connect to it (this is how PuTTY prevents other users on your server machine from connecting through the PuTTY proxy to your real X display). PuTTY also sends the server the details it needs to enable clients to connect, and the server should put this mechanism in place automatically, so your X applications should just work.

A common reason why people see one of these messages is because they used SSH to log in as one user (let’s say «fred»), and then used the Unix su command to become another user (typically «root»). The original user, «fred», has access to the X authentication data provided by the SSH server, and can run X applications which are forwarded over the SSH connection. However, the second user («root») does not automatically have the authentication data passed on to it, so attempting to run an X application as that user often fails with this error.

If this happens, it is not a problem with PuTTY. You need to arrange for your X authentication data to be passed from the user you logged in as to the user you used su to become. How you do this depends on your particular system; in fact many modern versions of su do it automatically.

10.15 «Network error: Software caused connection abort»

This is a generic error produced by the Windows network code when it kills an established connection for some reason. For example, it might happen if you pull the network cable out of the back of an Ethernet-connected computer, or if Windows has any other similar reason to believe the entire network has become unreachable.

Windows also generates this error if it has given up on the machine at the other end of the connection ever responding to it. If the network between your client and server goes down and your client then tries to send some data, Windows will make several attempts to send the data and will then give up and kill the connection. In particular, this can occur even if you didn’t type anything, if you are using SSH-2 and PuTTY attempts a key re-exchange. (See section 4.20.2 for more about key re-exchange.)

(It can also occur if you are using keepalives in your connection. Other people have reported that keepalives fix this error for them. See section 4.14.1 for a discussion of the pros and cons of keepalives.)

We are not aware of any reason why this error might occur that would represent a bug in PuTTY. The problem is between you, your Windows system, your network and the remote system.

10.16 «Network error: Connection reset by peer»

This error occurs when the machines at each end of a network connection lose track of the state of the connection between them. For example, you might see it if your SSH server crashes, and manages to reboot fully before you next attempt to send data to it.

However, the most common reason to see this message is if you are connecting through a firewall or a NAT router which has timed the connection out. See question A.7.8 in the FAQ for more details. You may be able to improve the situation by using keepalives; see section 4.14.1 for details on this.

Note that Windows can produce this error in some circumstances without seeing a connection reset from the server, for instance if the connection to the network is lost.

10.17 «Network error: Connection refused»

This error means that the network connection PuTTY tried to make to your server was rejected by the server. Usually this happens because the server does not provide the service which PuTTY is trying to access.

Check that you are connecting with the correct protocol (SSH, Telnet or Rlogin), and check that the port number is correct. If that fails, consult the administrator of your server.

10.18 «Network error: Connection timed out»

This error means that the network connection PuTTY tried to make to your server received no response at all from the server. Usually this happens because the server machine is completely isolated from the network, or because it is turned off.

Check that you have correctly entered the host name or IP address of your server machine. If that fails, consult the administrator of your server.

Unix also generates this error when it tries to send data down a connection and contact with the server has been completely lost during a connection. (There is a delay of minutes before Unix gives up on receiving a reply from the server.) This can occur if you type things into PuTTY while the network is down, but it can also occur if PuTTY decides of its own accord to send data: due to a repeat key exchange in SSH-2 (see section 4.20.2) or due to keepalives (section 4.14.1).

10.19 «Network error: Cannot assign requested address»

This means that the operating system rejected the parameters of the network connection PuTTY tried to make, usually without actually trying to connect to anything, because they were simply invalid.

A common way to provoke this error is to accidentally try to connect to port 0, which is not a valid port number.

I was trying to set up a simple backup script to run automatically that would copy a file from a Windows machine to a Linux one through SSH.

As a lot of simple online tutorials suggest I used pscp with a private key generated with puttygen and placed the corresponding public key (presented in copy/paste form by putty itself) in the authorized_keys file in Linux. This seems pretty straightforward considering that it worked in 2 other windows machines to a different Linux machine, with the same configuration.

There are no connectivity issues AFAICS and the same goes for ssh, considering I’m able to log in as root to the Linux machine. The config file (sshd_config) has the AuthorizedKeysFile set to ~/.sshd/authorized_keys.

The error «Server refused our key» keeps showing up, no matter what I do… The logs don’t show any authentication problems…

I’m planning to do more testing and setting the logLevel value to VERBOSE or DEBUG2 or 3 but considering the urgency of the matter and the fact that in order to actually test it on the machine I have to go through a lot of hassle considering the machine is in a place that is quite distant from my actual workplace…

Questions

  • Does anyone have any ideas?
  • Has this ever happened to anyone?

It seems like this might actually be a problem related to ssh versions or something of the sorts…

I was also considering the possibility that I need to have the public key inserted in the authorized_keys file inside the user’s .ssh directory (/user/.ssh/) besides having it in root’s folder (doesn’t make much sense because of the value of AuthorizedKeysFile in sshd_config).

I’ve done some teting with the ssh server’s LogLevel set o VERBOSE but I could’nt retrieve the information (liability issues), so instead here goes an output/debug log from another source which seems to be displaying the same error…

Connection from 192.168.0.101 port 4288
debug1: Client protocol version 2.0; client software version OpenSSH_4.5
debug1: match: OpenSSH_4.5 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.5
debug1: permanently_set_uid: 22/22
debug1: list_hostkey_types: ssh-rsa,ssh-dss
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST received
debug1: SSH2_MSG_KEX_DH_GEX_GROUP sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_INIT
debug1: SSH2_MSG_KEX_DH_GEX_REPLY sent
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: KEX done
debug1: userauth-request for user dcowsill service ssh-connection method none
debug1: attempt 0 failures 0
debug1: PAM: initializing for "dcowsill"
debug1: userauth-request for user dcowsill service ssh-connection method publickey
debug1: attempt 1 failures 1
debug1: test whether pkalg/pkblob are acceptable
debug1: PAM: setting PAM_RHOST to "192.168.0.101"
debug1: PAM: setting PAM_TTY to "ssh"
debug1: temporarily_use_uid: 1052/105 (e=0/0)
debug1: trying public key file /testuser/.ssh/authorized_keys
debug1: restore_uid: 0/0
debug1: temporarily_use_uid: 1052/105 (e=0/0)
debug1: trying public key file /testuser/.ssh/authorized_keys
debug1: restore_uid: 0/0
Failed publickey for dcowsill from 192.168.0.101 port 4288 ssh2
debug1: userauth-request for user dcowsill service ssh-connection method publickey
debug1: attempt 2 failures 2
debug1: test whether pkalg/pkblob are acceptable
debug1: temporarily_use_uid: 1052/105 (e=0/0)
debug1: trying public key file /testuser/.ssh/authorized_keys
debug1: restore_uid: 0/0
debug1: temporarily_use_uid: 1052/105 (e=0/0)
debug1: trying public key file /testuser/.ssh/authorized_keys
debug1: restore_uid: 0/0
Failed publickey for dcowsill from 192.168.0.101 port 4288 ssh2
Connection closed by 192.168.0.101

It seems like the program is trying to open the authorized_keys file with permissions from the owner, but then there is no more information on what is generating the problem.
One last thing, I’ve checked and double-checked the file and foler permissions and they’re all ok.

openssh-logo Настройка SSH авторизации только через RSA ключи не особо сложный процесс, но имеет свои нюансы. Первый и самый главный — это безопасность SSH авторизации по RSA ключам.

Почему я не люблю SSH авторизацию по RSA ключам? SSH авторизация по RSA ключам удобна, но считаю её недостаточно безопасной из-за открытости приватного ключа, а особенно если на приватном ключе нет пароля — т.е. приватный ключ доступен почти для всех программ запущенных в ОС и его утечка из файловой системы более вероятна чем утечка пароля из мозга!

При всех антивирусах, сетевых мониторах на шлюзах и в самой ОС, системах превентивного обнаружения вторжений и прочих мерах безопасности сервера или рабочей станции, которые часом приобретают параноидальные признаки — поставить 100% на то, что на машине нет, или не появится в ближайшем будущем, какой-то стучащей хрени, невозможно.

В безопасности своей рабочей машины я уверен на 99.99%, пока всё идёт хорошо (обновление всего всегда ручное, автоматически на моём ПК только время синхронизируется, входящие/исходящие жестко зафильтрованы, браузеры все в песочнице, во временных каталогах запрещена экзекуция исполняемых и т.д.), но тем не менее из-за нехватки 1-го процента уверенности не могу себе позволить SSH авторизацию по RSA ключам.

Кто-то может возразить, мол «Да, но на приватный ключ можно поставить пароль!» — согласен, можно, но в таком случае пароль будет зашит в сам ключ, что при его краже, а также достаточных вычислительных ресурсах и хороших знаниях криптографии, даст возможность для его активного брутфорса без каких либо ограничений со стороны ОС — т.е. брутфорс ОС выполнить намного сложнее (блокировка доступа после 2-3 неверных попыток входа, и пр.), чем брутфорс ключа локально!

Также если будет утерян приватный (id_rsa), то мы смело может помахать серванту ручкой и пойти с горя синевы наклюкаццо (when SSH private keys are lost) если нет физического доступа к машине — публичный (id_rsa.pub) можно восстановить из приватного, а вот приватный из публичного вряд ли… Есть некая фича отзыва (RevokedKeys) ключей, но это не одно и тоже, что восстановление — отозванные (аннулированные) ключи не могут использоваться для дальнейшей аутентификации (Revoked keys cannot be used for user or host authentication and will trigger a warning if used.)!

Автор поста остался при своём мнении — SSH авторизация по RSA ключам менее безопасна, чем авторизация по паролю, например:

  1. при парольной авторизации, угроза снифинга интернет трафика, но тут мы можем использовать дополнительный SSL туннель — вероятная приватность 99%;
  2. при авторизации по ключам, угроза утечки приватного ключа разом с паролем от королевства — вероятная приватность 50/50%;

Только не говорите, что взлом SSL трафика или брутфорс приватного RSA ключа невозможен — немцы во вторую мировую тоже думали, что шифровальная машина Энигма вермахта непобедима!

Если кто всё же решился использовать механизм SSH аутентификации только на одних RSA ключах, с запретом парольного механизма, тогда выполняем пару несложных шагов, что описаны ниже, а также пишем завещание, одеваем памперсы и держим труселя покрепче!;)

Создание пары RSA ключей

Создание пары RSA ключей не займёт много времени — ssh-keygen-им RSA ключи:

-bash-4.2$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/shaman/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/shaman/.ssh/id_rsa.
Your public key has been saved in /home/shaman/.ssh/id_rsa.pub.
The key fingerprint is:
72:b9:9a:395:b2:774:8c:59:62:90:4f:a9:03:80 shaman@openbsd.localhost
The keys randomart image is:
+--[ RSA 2048]----+
| .               |
|E .              |
|   .   . .       |
|    . o o.       |
|     ..*S        |
|      +o*.o      |
|     . =.B .     |
|      o++ +      |
|     .+. .       |
+-----------------+
-bash-4.2$

Тут мы вошли в консоль как пользователь «shaman», домашний каталог «/home/shaman», в котором по умолчанию расположен каталог .ssh с RSA ключами (id_rsa и id_rsa.pub). В примере пароль на приватный ключ не ставили, но для применения на практике желательно поставить хоть какой-то пароль на id_rsa (секретный ключ).

Копируем содержимое публичного ключа в файл содержащий авторизированные ключи:

cat ~/id_rsa.pub >> ~/authorized_keys

Разумеется все описанные здесь манипуляции, создание RSA ключей и т.п., выполняются на удалённом сервере, на котором мы и собираемся проходить аутентификацию по ключам.

Ключи можно создать и на локальной машине, но потом публичный ключ нужно будет перенести на удалённую…

Конфигурация sshd_config

Под занавес не помешает заглянуть в /etc/ssh/sshd_config и проверить всё ли там готово для авторизации по ключам:

# The default requires explicit activation of protocol 1
Protocol 2
 
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
 
RSAAuthentication yes
PubkeyAuthentication yes
 
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile    %h/.ssh/authorized_keys

Если собрались отключить логин по паролю, тогда в /etc/ssh/sshd_config отключаем:

PasswordAuthentication no
PermitRootLogin no

PuTTY Unable to use key file

Для тех, кто в первый раз на лыжах PuTTY — ошибка «Unable to use key file «X:id_rsa» (OpenSSH SSH-2 private key)» может возникать по нескольким причинам:

  • Неформат SSH версии в которой ковался id_rsa ключ и версии в которой он пытается использоваться, для SSH-1 и SSH-2 ключи куются в разных форматах;
  • Неформат id_rsa ключа для использования в PuTTY, для PuTTY нужно ключи конвертировать в .ppk формат

Если id_rsa генерировался стандартными утилитами из пакета OpenSSH (ssh-keygen -t rsa), то для его использования в SSH клиенте PuTTY он должен быть экспортирован в .ppk формат следующим образом (CMD вариант — puttygen id_rsa -o id_rsa.ppk):

  1. Запускаем puttygen и загружаем туда наш id_rsa приватный ключ, что был создан утилитами из пакета OpenSSH, и, если хотим, ставим на него пароль:
    convert-id_rsa-private-key-to-ppk-format_1
  2. Сохраняем приватный ключ в формате .ppk (Save private key):
    convert-id_rsa-private-key-to-ppk-format_2

Теперь после попытки авторизации по ключу нам достаточно будет ввести логин, а если ставили пароль на приватный ключ, то и пароль от приватного ключа соответственно:

login as: shaman
Authenticating with public key "imported-openssh-key"
Last login: Sat Jan  4 09:50:16 2014 from 192.168.231.1
OpenBSD 5.4 (GENERIC) #37: Tue Jul 30 12:05:01 MDT 2013
 
Welcome to OpenBSD: The proactively secure Unix-like operating system.
 
Please use the sendbug(1) utility to report bugs in the system.
Before reporting a bug, please try to reproduce it with the latest
version of the code.  With bug reports, please try to ensure that
enough information to reproduce the problem is enclosed, and if a
known fix for it exists, include that as well.
 
-bash-4.2$

-------------
 
login as: sham
Authenticating with public key "imported-openssh-key"
Passphrase for key "imported-openssh-key":
Last login: Sat Jan  4 09:50:16 2014 from 192.168.231.1
OpenBSD 5.4 (GENERIC) #37: Tue Jul 30 12:05:01 MDT 2013
 
Welcome to OpenBSD: The proactively secure Unix-like operating system.
 
Please use the sendbug(1) utility to report bugs in the system.
Before reporting a bug, please try to reproduce it with the latest
version of the code.  With bug reports, please try to ensure that
enough information to reproduce the problem is enclosed, and if a
known fix for it exists, include that as well.
 
-bash-4.2$

Восстановить публичный ключ от приватного

Для восстановления публичного ключа (Create a public SSH key from the private key) от уже имеющегося приватного выполним:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

Авторизация по ключам в OpenSSH server for Windows

Windows не Linux, а Linux не Windows. В принципе авторизация по ключам в OpenSSH server for Windows работает аналогично Linux/BSD, но с некоторыми существенными отличиями.

Если в конфигурации сервера по умолчанию используется запись вида «AuthorizedKeysFile .ssh/authorized_keys», то файл авторизированных ключей authorized_keys сервер будет искать в домашнем каталоге пользователя, в директории .ssh.

При такой конфигурации OpenSSH server for Windows мы можем столкнутся с ошибкой SSH клиента «OpenSSH Server refused our key«, а системный журнал получим сообщения:

Не найдено описание для события с кодом ( 0 ) в источнике ( sshd ). Возможно, на локальном компьютере нет нужных данных в реестре или файлов DLL сообщений для отображения сообщений удаленного компьютера. Попробуйте использовать ключ /AUXSOURCE= для получения этого описания, — дополнительные сведения об этом содержатся в справке. В записи события содержится следующая информация: sshd: PID 1712: error: Received disconnect from 192.168.231.1: 13: Unable to authenticate.

Не найдено описание для события с кодом ( 0 ) в источнике ( sshd ). Возможно, на локальном компьютере нет нужных данных в реестре или файлов DLL сообщений для отображения сообщений удаленного компьютера. Попробуйте использовать ключ /AUXSOURCE= для получения этого описания, — дополнительные сведения об этом содержатся в справке. В записи события содержится следующая информация: sshd: PID 1712: Authentication refused: bad ownership or modes for directory /home/user.

Вероятно, что ошибку SSH клиента «OpenSSH Server refused our key» будем получать неизбежно и постоянно если будем пытаться использовать персональный файл «.ssh/authorized_keys» для каждого пользователя!

Какие права на домашний каталог пользователя не пробовал ставить, всё равно в SSH клиенте получаю «OpenSSH Server refused our key», а в системном журнале «sshd: PID 1712: Authentication refused: bad ownership or modes for directory /home/user» — это вероятно связано разделением прав в cygwin окружении, т.е. не при каких условиях не даёт читать домашний каталог пользователя, пока тот не пройдёт авторизацию…

Единственным выходом в этом случае является использование общего, для всех пользователей, файла authorized_keys — «AuthorizedKeysFile /etc/ssh/authorized_keys«.

Каждый пользователь может создавать свои собственные ключи, в своём домашнем каталоге:

C:OpenSSHdbin>ssh-keygen -t rsa -f /home/%username%/.ssh/id_rsa
Generating public/private rsa key pair.
Created directory '/home/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/root/.ssh/id_rsa.
Your public key has been saved in /home/root/.ssh/id_rsa.pub.
The key fingerprint is:
9e:f8:4f:55:1a:5a:83:a9:b9:4f:5f:5d:41:28:14:1b root@local-cab12c5d9
The key's randomart image is:
+--[ RSA 2048]----+
|           E.o...|
|            ..o. |
|             ... |
|              . .|
|        So   o  .|
|       oo.+ o. . |
|      .o++ o. .  |
|      oo....     |
|      .oooo      |
+-----------------+
 
C:OpenSSHdbin>

Но, для разрешения доступа по ключам только администратор должен добавить содержимое публичного ключа (id_rsa.pub) каждого пользователя в /etc/ssh/authorized_keys, ну, и разумеется не забываем добавить пользователя в /etc/passwd.

Ссылки по теме:

  • Chapter 8: Using public keys for SSH authentication

I have created a key pair using PuTTy, but when I try connecting to my Vultr instance, I get the error ” server refused our key”. What’s wrong here?

That was a recent support received from one of the customers as part of the Managed Cloud Services that we provide.

Server owners often face this error when accessing the server using SSH keys. And, this error can occur due to wrong format of SSH keys, wrong permissions of SSH key, and more.

Today, we’ll discuss the top 3 reasons for this error and how our Dedicated Engineers fix them.

‘Server refused our key’ on Vultr instance – What this means?

Key based authentication is a secure way to access the server. Here, the public key is placed on the Vultr instance while the private key is placed on the user’s computer.

The error “Server refused our key” on Vultr instance clearly shows that the server rejected the SSH key submitted for login.

Here, our Support Engineers recreate the problem by connecting to the server via SSH in debug mode.

ssh -v xx.xx.xx.xx

It will give a detailed trace that will help us to analyze the problem. Further, we change the log level to debug mode in the SSH configuration file /etc/sshd/ssh_config.

LogLevel DEBUG3

Then, we check the SSH logs(/var/log/secure and /var/log/auth.log) to find the origin of the issue.

Server refused our key on Vultr instance – Causes & Fixes

Now, let’s see the main reasons for this error and how our Dedicated Engineers fix them.

1) Wrong permissions of SSH key

SSH server login requires strict permissions for the key files used.

In other words, if the user has no proper privileges to read the SSH keys, then SSH refuses to authenticate. Similarly, if any of the files in .ssh folder can be written by other users, the error ‘server refused our key ‘may occur.

How we fix?

Firstly, our Support Experts check and confirm that the public key is properly placed in the .ssh folder of the user’s home directory, and proper ownership are assigned to these files

Further, we confirm that the permissions and ownership of the SSH key files are correct. In other words, we ensure that the permissions of the .ssh folder and its parent folder is 700. This ensures that the user only has the write privileges to this folder.

Similarly, we ensure that the permissions of the private key on the client side is set to 600 or more restrictive rights. We also ensure that the public key file in .ssh/authorized_keys should have permission 600, so that other users can’t write the key.

2) Wrong SSH key format

Another common reason for this error is customer uses wrong public key format. This usually happens when users create the SSH key using puttygen in Windows and copy it to Linux. This is because, Windows splits the public key in multiple lines. But, Linux or OpenSSH systems can’t understand this public key format and throws the error server refused our key on Vultr instances.

And, users see an error like this in the SSH logs(/var/log/secure or /var/log/auth.log).

sshd: error: key_read: uudecode AAAAB3N [etc etc etc until about 3/4 of my public key]
How we fix?

Here, our Support Engineers confirm the way customers generate the SSH keys for the user. Further, we analyze the public key format and correct if any problems noted. For example, we use the below command to convert the public key to a format understood by the OpenSSH server.

ssh-keygen -i -f windowspub.key

Moreover, we confirm that the SSH keys are all in a single line and there are no leading or trailing spaces in the SSH keys.

3) SSH configuration issues

Similarly, problems in the SSH configuration file can also lead to this error. We’ve seen instances where users add SSH keys on their Vultr instance. But, failed to enable Public key authentication in the SSH configuration file. As a result, users see the error ‘server refused our key’ on their Vultr instance.

How we fix?

In such cases, our Support Engineers enable public key authentication in the SSH configuration file /etc/sshd/ssh_config. For instance, we add the following line to enable key based authentication.

PubkeyAuthentication yes

In addition to that, we also ensure that the location of the key file is enabled.

AuthorizedKeysFile .ssh / authorized_keys

Most importantly, we restart the SSH service on the Vultr instance to bring these changes into effect.

[And, do you need a Server Expert to fix your SSH connection issues on your Vultr VPS. We can help you here.]

Conclusion

In short, server refused our key error on a Vultr instance can occur due to wrong format of the SSH key, incorrect permissions of the SSH key, and so on. Today, we’ve discussed the top 3 reasons for this error and how our Support Engineers fix them.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Писал заметочку о CentOS на VPS дошёл до ssh авторизации по ключу. и нормально так встрял аж на две недели)), забегая вперёд скажу, что ошибка была наивная и от того досадной)), но было интересно!

Ну-с, начнём по-порядку расписывать картину моего позора))

  1. Сгенерировал ключики в путти-ген

putty-gen1 putty-gen2 putty-gen3

  1. публичный закинул в хом

pscp

  1. настройки sshd_config

вытягиваем sshd_config

pscp-dl

рассматриваем то, что есть. Оставляем то, что нужно.

# $OpenBSD: sshd_config,v 1.90 2013/05/16 04:09:14 dtucker Exp $
 # This is the sshd server system-wide configuration file. See
 # sshd_config(5) for more information.
 # This sshd was compiled with PATH=/usr/local/bin:/usr/bin
 # The strategy used for options in the default sshd_config shipped with
 # OpenSSH is to specify options with their default value where
 # possible, but leave them commented. Uncommented options override the
 # default value.
 # If you want to change the port on a SELinux system, you have to tell
 # SELinux about this change.
 # semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
 #
 Port 2
 AddressFamily inet
 Protocol 2
 HostKey /etc/ssh/ssh_host_rsa_key
 HostKey /etc/ssh/ssh_host_ecdsa_key
 SyslogFacility AUTHPRIV
 PermitRootLogin yes
 RSAAuthentication yes
 PubkeyAuthentication yes
 AuthorizedKeysFile .ssh/authorized_keys
 PasswordAuthentication yes
 PermitEmptyPasswords no
 GSSAPIAuthentication yes
 GSSAPICleanupCredentials yes
 UsePAM yes
 X11Forwarding no
 UsePrivilegeSeparation sandbox # Default for new installations.
 AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
 AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
 AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
 AcceptEnv XMODIFIERS
 Subsystem sftp /usr/libexec/openssh/sftp-server
 AllowUsers root discipulus

4 смена порта

в секции Port пишем нестандартный порт (отобьёт немалую часть срача в логи на предмет неудачной авторизации армии ботов))

5 настройка iptables

не забиываем отметить изменение порта (я так пару раз переустанавливал системы)).

6 PubKeyAuthentication yes

явно указываем аутентификацию по ключу.

7 PasswordAuthentication yes

это отключаем в последнюю очередь

9 user — server refused our key

и вот на этом я встрял — ситуация такова: рут с ключами заходит — пользователь (группа wheel) по ключам не заходит, только по паролю.

Что я только не делал, все рецептики предлагаемые в рунете были вычитаны, осмыслены, применены и нифига)) рут — всё ок, юзер — болт.

Я потерял покой и сон.

Далее пара моментов, которые не помогли в решении, но показались интересными

10 AddressFamily

отключаем поддержку ipv6

[root@discipulus74 ssh]# netstat -tulpn | grep sshd
tcp 0 0 0.0.0.0:2 0.0.0.0:* LISTEN 458/sshd
tcp6 0 0 :::2 :::* LISTEN 458/sshd
[root@discipulus74 ssh]# service sshd restart
Redirecting to /bin/systemctl restart sshd.service
[root@discipulus74 ssh]# netstat -tulpn | grep sshd
tcp 0 0 0.0.0.0:2 0.0.0.0:* LISTEN 603/sshd
[root@discipulus74 ssh]#

11 Очень занятная опция Match

И заодно настроил SFTP.

Проблема была в преднастроенном профиле PuTTY. Профиль для рута был настроен верно, с правильными путями к секурному ключу. А вот профиль пользователя был настроен с путями к старому ключу, не соответствующего паре публичного ключа на сервере)) вот такой я тормаз!

UPD — настройка PuTTY для нормального отображения псевдографики в консоли
Terminal > Keyboard > «The Function keys and keypad» = linux
Window > Translation > Character set — выставляем правильную кодировку
Connection > Data > «Terminal-type string» пишем linux

Понравилась статья? Поделить с друзьями:
  • Openssh client windows 10 что это
  • Openssh authentication agent что это за служба windows 10
  • Openservice ошибка 5 отказано в доступе windows 10
  • Openserver оптимизировать windows для работы с ssd
  • Openserver невозможно занять порт 80 поскольку он уже используется службы windows