12

I'm trying to connect to another machine using PHP's ssh2 functions. I know the ssh keys have been created with no passwords and are distributed correctly, I can ssh user@host in the terminal on my machine to the server.

The PHP function tries to connect to a ip address using an ssh key file:-

 function minnerConnect($miner_serial) {

    $port = '7822';
    $miner_ip = $this->getMinerIp($miner_serial);

    $methods = array(
        'kex' => 'diffie-hellman-group1-sha1',
        'hostkey' => 'ssh-dss',
        'client_to_server' => array(
            'crypt' => '3des-cbc',
            'mac' => 'hmac-md5',
            'comp' => 'none'),
        'server_to_client' => array(
            'crypt' => '3des-cbc',
            'mac' => 'hmac-md5',
            'comp' => 'none'));
    $connection = ssh2_connect($miner_ip, $port, $methods);
    if (ssh2_auth_pubkey_file($connection, 'root',
        '/root/.ssh/id_dsa.pub',
        '/root/.ssh/id_dsa','')) {
      echo "Public Key Authentication Successful\n";
    } else {
      echo "Public Key Authentication Failed";
    }

but the error shown is:-

( ! ) Warning: ssh2_auth_pubkey_file(): Authentication failed for root using public key: Callback returned error in /var/www/application/models/miner_model.php on line 95

line 95 is '/root/.ssh/id_dsa','')) {.

Can anybody suggest a fix?

drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59
James Kirkby
  • 1,716
  • 5
  • 24
  • 46

1 Answers1

12

The error in this case was that the keys were generated by the root user, but they need to be accessible by the web server group/owner www-data.

I didn't like the idea of keeping ssh keys in a web folder open to www-data, so I moved the key files to a new user's home directory (/home/keyuser/) then made them accessible to www-data. Authentication was successful.

Even though the original error was saying it found the file, it couldn't read the file.

A better debug method is to try reading the file via php:

$prv_key = file_get_contents('/var/www/application/files/id_dsa');
print "<pre>";
var_export($prv_key);
print "</pre>";
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
James Kirkby
  • 1,716
  • 5
  • 24
  • 46
  • 1
    Note to people trying to get this to work with a password. This won't work with a password set on the private key due to a bug (http://php.net/manual/en/function.ssh2-auth-pubkey-file.php). – Fractalf Nov 10 '15 at 12:44
  • Note2, if you still can't get it working, it might be the key format, I resolved with `ssh-keygen -m PEM -t rsa` ;) – Syco Nov 02 '20 at 17:22