php run git got “ssh Permission denied”
my php script:
<?php $output=array(); $returnVar=0; chdir("/var/www/html"); exec('git pull firstname.lastname@example.org:andrewadel.git master 2>&1', $output , $returnVar); // exec('pwd', $output , $returnVar); echo "<pre>\n"; echo "return status: $returnVar\n\n"; print_r($output); echo "</pre>\n";
when I manually run the script as “apache”, everything is fine
bash-4.1$ whoami apache bash-4.1$ php gitsync.php <pre> return status: 0 Array (  => From git.assembla.com:andrewadel  => * branch master -> FETCH_HEAD  => Already up-to-date. ) </pre>
When I run it from a browser, it fails
http://188.8.131.52/gitsync.php?111 return status: 1 Array (  => ssh: connect to host git.assembla.com port 22: Permission denied  => fatal: The remote end hung up unexpectedly )
4 Solutions collect form web for “php run git got “ssh Permission denied””
A lot of variables here… but I faced pretty much exact same behavior with a remote cgi script I was working on.
In my case the issue was related to SELinux on CentOS.
user@remoteserver:~$ getsebool -a | grep httpd
... httpd_can_network_connect --> off ...
Test Possible Fix(sudo or run as root):
user@remoteserver:~$ setsebool httpd_can_network_connect=1 //...then initiate your serverside script remotely
Permanent Fix(if above has proven effective):
user@remoteserver:~$ setsebool -P httpd_can_network_connect=1
-P option ensures subject SELinux boolean value is set to specified value as default on future reboots.
man getsebool and
Is your webserver and PHP installation enforced by Suhosin, safe-mode, Apparmor or other security mechanisms?
And I recommend trying PHP-Git bindings like php-git if you’re doing more operations. That module is designed for working with Git in PHP code.
Apache would run the script as the ‘nobody’ user. Your script relies on having the private key most likely stored at ~apache/.ssh/id_rsa
The failure is that git can’t access that key and isn’t able to authenticate itself against the git server.
The solution is to specify the correct key to use and make that key accessible to the user that is executing the script.
Read this for how to specify the key:
Specify private SSH-key to use when executing shell command with or without Ruby?
Take a look here for an approach to running as a different user:
I would not recommend running as nobody (since then the nobody user has access to your private key), or as apache (since then you are increasing the damage that could be done should an exploit be found for your site). Therefore you should create a different user with the minimal permissions to read your private key and execute the git command. It may not be necessary to specify the key if you just create a limited user account for this and put the keys (public/private) into ~/.ssh
Is this a permissions issue? A PHP script would be run as the nobody user most likely, which may not have permissions to run the git command.