Help
Help

Reputation: 13

Authenticate to SFTP server in PHP with PuTTY .ppk key file

I want to transfer files via SFTP using PHP.

The remote server provides the IP, username, and a password including PPK file with a passphrase. I'm able to log in using WinSCP, but in my php script I'm having trouble with ssh2_auth_pubkey_file()

Can you please tell me what Im supposed to do with the given PPK file? What are the public and private key I need to provide to authenticate?

Clear explanation is much appreciated. Thank you!

Code:

$conn = ssh2_connect($host, $port, array('hostkey'=>'ssh-rsa'));
if(ssh2_auth_pubkey_file($conn,$username,$pub_key,$pri_key,$passphrase)){
  echo "Public Key Authentication Successful\n";
}else{
  die('Public Key Authentication Failed');  
}

The public key I used came from PuTTYgen. Converted PPK to PUB file.

Upvotes: 0

Views: 3798

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202612

Function ssh2_auth_pubkey_file accepts public and private key files in a common OpenSSH format.

To generate these files from PuTTY .ppk key file:

  • Start PuTTYgen and load your .ppk key.
  • Use contents of Public key for pasting into OpenSSH authorized_keys file for a public key file.
  • Use Conversions > Export OpenSSH key menu command to generate private key file.

It does not matter where you save the files, as long as the webserver can access those.


There seems to be a bug in PHP SSH2 functions that prevents loading encrypted private keys (keys with passphrase).

The bug results in:

ssh2_auth_pubkey_file(): Authentication failed for ... using public key: Callback returned error


If you want to use the private key, and you cannot fix SSH libraries, you can use phpseclib instead.

set_include_path("phpseclib");
require_once("Net/SSH2.php");
require_once("Crypt/RSA.php");

$privatekey = new Crypt_RSA();
$privatekey_data = file_get_contents($pri_key);

$privatekey->setPassword($passphrase);
if (!$privatekey->loadKey($privatekey_data, CRYPT_RSA_PRIVATE_FORMAT_PKCS1))
{
    die("Cannot load key");
}

$sftp = new Net_SSH2($host);

if (!$sftp->login($username, $privatekey))
{
    die("Cannot login");
}

phpseclib supports even .ppk keys, though I was not able to use encrypted .ppk key either. But encrypted OpenSSH keys works correctly. Note that you do not need a separate public key file with phpseclib.

Upvotes: 1

Related Questions