PHP ssh2_auth_pubkey_file(): Authenticatio

2019-05-04 06:10发布

问题:

In PHP5.3.3 (on CentOS and apache2) I am attempting to connect to a SFTP via a php script. The code grabs the keys and server details from the constructor

function __construct(){
    $this->host     = 'servername.loc';
    $this->port     = SFTP_PORT;
    $this->auth_user    = 'username';
    $this->auth_pub     = '/data/home/username/.ssh/id_rsa.pub';
    $this->auth_priv    = '/data/home/username/.ssh/id_rsa';
    $this->auth_pass    = null;
    $this->connection   = null;
}

and uses those details to create the connection.

    private function connect(){
    if (!($this->connection = ssh2_connect($this->host, $this->port))) {
        $this->response  = array('code' => "20",
                                 "message" => "Error connecting to SFTP server.");
        return false;
    }
    if (!ssh2_auth_pubkey_file($this->connection, $this->auth_user, $this->auth_pub,
                                $this->auth_priv, $this->auth_pass)) {
        $this->response  = array('code' => "40",
                                 "message" => "Error authenticating to SFTP server with key.");
        $this->disconnect();
        return false;
    }
}

The result I get is an error on the call to ssh2_auth_pubkey_file().

The error is:

"ssh2_auth_pubkey_file(): Authentication failed for USERNAME using public key: Invalid key data, not base64 encoded"

There is no password on the key, and I can use these keys via CLI ssh to connect to the server manually.

I am stumped. Do I need to encode the keys somehow? Suggestions?

回答1:

The prerequisite that you mention, namely the pubkey file not to have any comments and not even have a trailing newline is incorrect (and the newline thingy absurd when you think it through).

If your scriptfails, you have prob. sooner stumbled into the ssh2 bug that makes ssh2 fail when it is compiled wuth libgcrypt instead of openssl. The workaround is to create a PEM formatted copy of your private key file in PEM format with openssl:

~/.ssh> openssl rsa -in id_rsa -out id_rsa.pem

Then, in ssh2_auth_pubkey_file() in your PHP script, use id_rsa.pem as privkey file instead of id_rsa, and omit the passphrase. That should make it work.



回答2:

Well, it figures, I find the answer after asking the question openly. Found this on another site with dev comments.

d23d23 at gmail dot com said: "The public key must be on one line starting with the key type, 1 space and followed by the keydata (no newlines) and not followed by comments. This is a limitation of libssh2, so remove any excess data from the file after creating it with your key generation tools."

So even though I used openssl to create the private key and public key, I had to edit it to put it all on one line with the key type as noted above. Thanks.



标签: php ssh