ConFoo Montreal 2026: Call for Papers

Voting

: nine minus four?
(Example: nine)

The Note You're Voting On

gramo dot gnu at gmail dot com
15 years ago
I had an anoyiing problem with this function, everytime I tried to make it run it responds with an

Authentication failed for <user> using public key

but when I try directly to connect to the server using
ssh <user>@<domain>
Things works fine...

After lots of intents I realize that local files were read protected from user apache (they were stored at /home/<user>/.ssh directory)

So, if you also have this problem, just make a new directory into a place where apache can read and place there the keys.

The whole thing I do is as follows (Linux & Apache both server and client):

First I create a directory where apache can read

mkdir ~/.newssh_keys
chmod 777 ~/.newssh_keys

(This is a security issue, so maybe you need to realize how to make it safer.)

Then I create keys into local server choosing ~/.newssh_keys/id_dsa as the file to save the key:

ssh-keygen -t dsa
...
Enter file in which to save the key (/home/<user>/.ssh/id_dsa): ~/.newssh_keys/id_dsa
...

Then I have to change permissions to private key
(This is a security issue, so maybe you need to realize how to make it safer.)

chmod 644 ~/.newssh_keys/id_dsa

I copy the public key into the server's .ssh directory
client$ scp id_dsa.pub <remoteuser>@<server_domain>:~/.ssh/

and then I connect myself to the server using traditional ssh in order to append the public key at the end of authorized_keys2 file

server$ cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2

and remove the public key in order to be clean
server$ rm ~/.ssh/id_dsa.pub

Finally I use this code into my php script

<?php
// This in order to be sure apache can read public key
// (remove this after debug)
$pub_key = file_get_contents('~/.newssh_keys/id_dsa.pub');
print
"<pre>";
var_export($pub_key);
print
"</pre>";

// This in order to check private one
// (remove this after debug)
$prv_key = file_get_contents('~/.newssh_keys/id_dsa');
print
"<pre>";
var_export($prv_key);
print
"</pre>";

// Finally the connection code
$connection = ssh2_connect('<server_domain>', 22, array('hostkey', 'ssh-dss'));
if (
ssh2_auth_pubkey_file($connection, '<server_user>',
'~/.newssh_keys/id_dsa.pub',
'~/.newssh_keys/id_dsa')) {
echo
"Public Key Authentication Successful\n";
} else {
echo
"Public Key Authentication Failed";
}
?>

<< Back to user notes page

To Top