Question

Authentication failed for root using public key when using ssh2_auth_pubkey_file()

Posted May 20, 2020 790 views
PHP

I am trying to use ssh using the public key on PHP. I created ssh keys and assigned to droplet successfully. And I can access the root on the terminal without any issue.

As there is a permission issue, I copied the keys to /var/www/html/.

But I am getting an error “ssh2authpubkey_file(): Authentication failed for root using public key:”

Here is my code:

$host = ‘127.0.0.1’; //Droplet ip
$port = 22;
$user = 'root’;
$pass = 'pass’;
$pubkey = ’./.ssh/idrsa.pub’;
$prikey = ’./.ssh/id
rsa’;

$conn = ssh2connect( $host, $port );
$auth = ssh2
authpubkeyfile( $conn, $user, $pubkey, $prikey, $pass );

if ( $auth )
{
echo 'Public Key Authentication Successful.’ . PHPEOL;
}
else
{
echo 'Public Key Authentication Failed.’ . PHP
EOL;
}

Please help.

1 comment
  • Sorry code was not formatted. Here is the formatted code

    $host   = '127.0.0.1'; //Droplet ip
    $port   = 22;
    $user   = 'root';
    $pass   = 'pass';
    $pubkey = './.ssh/id_rsa.pub';
    $prikey = './.ssh/id_rsa';
    
    $conn   = ssh2_connect( $host, $port );
    $auth   = ssh2_auth_pubkey_file( $conn, $user, $pubkey, $prikey, $pass );
    
    if ( $auth )
    {
        echo 'Public Key Authentication Successful.' . PHP_EOL;
    }
    else
    {
        echo 'Public Key Authentication Failed.' . PHP_EOL;
    }
    

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
2 answers

Hi @rahulna.

The error in this case seems to be that the keys were generated by the root user, but they need to be accessible by the web server group/owner, usually - www-data. To confirm this, you can try and use the file_get_contents method and dump the result from the command using var_dump most probably it would say it doesn’t have enough permissions.

I’ll recommend configuring the key’s ownership and permissions to be accessible from the user that’s being used by your WebService -either Apache or Nginx.

Regards,
KDSys

  • Thanks for the reply.
    Yes, the key is generated by the root user. But I copied the key files to www directory(I know it is not a good idea, this is for testing) var_dump is displaying the key contents perfectly. So it will not be a permission issue.

Show answer This answer has been marked as resolved by rahulna.
Submit an Answer