Search code examples
phpsshssh-keys

Why does PHP's ssh2_auth_pubkey_file require a public key?


I can log into a server using only a private key via command line. Why does this PHP function require a public key also?

$connection = ssh2_connect($server_address, $port, array('hostkey'=>'ssh-rsa'));
if (!@ssh2_auth_pubkey_file($connection, $username, $public_key_path, $private_key_path, $password))
{
  echo '<h3 class="error">Unable to authenticate. Check ssh key pair.</h3>';
  break;
}
echo '<h3 class="success">Authenticated.</h3>';

I am working on a personal use test script to check firewall settings and access permissions as I adjust and deploy new servers. I'm mostly just curious as this seems to indicate I am missing some information about how ssh works. But I'm also annoyed that I have to give two paths when it seems I should only need one.


Solution

  • I do not have a direct experience with PHP SSH2 functions. But PHP ssh2_auth_pubkey_file internally calls libssh2_userauth_publickey_fromfile_ex from libssh2, whose documentation says about the publickey parameter:

    Path name of the public key file. (e.g. /etc/ssh/hostkey.pub). If libssh2 is built against OpenSSL, this option can be set to NULL.

    So maybe you can pass null in PHP (as PHP builds against OpenSSL). If not, it's only a limitation of PHP SSH2 API. Not a something that comes intrinsically from SSH as such.


    For the reason why SSH APIes usually allow specifying a separate public key file, when key-pair file (usually not-really-correctly called private key file) is enough, see my answer to:
    Purpose of pubkey parameter of JSch.addIdentity

    I believe that given the PHP SSH API, the argument is rather useless, as the API does not even allow you to have multiple keys loaded and you have to specify the passphrase upfront anyway.