Friday, March 5, 2010

SSH tunnelling using PHP

Copyleft@shah.devendra
I want to share my knowledge for ssh tunneling using PHP. There are various tools like SSH2 client, phplibsec. Unfortunately none of those tools worked for me good. So finally I came out with my own easy solution. Hope it will be helpful for you. If you have any kind of questions and suggestions please contact me at erdevendra@gmail.com


Step 1: SSH without prompting for password from Host_Src to Host_Dst

Host_Src # ssh-keygen -t rsa
Host_Src # cd /root/.ssh

Transfer the id_rsa.pub file to host_dest by either ftp, scp, rsync or any other method
Host_Src# sftp [ip address of Host_Dst]
ftp> put id_rsa.pub
ftp> bye

Host_Dst# cat id_rsa.pub >> ~/.ssh/authorized_keys
Host_Dst# chmod 700 ~/.ssh/authorized_keys


[ Note: SSH by default doesn’t allow root log in. This has to be explicitly enabled on Host_Dst. This can be done by editing /etc/ssh/sshd_config and changing the option of PermitRootLogin from no to yes.]

[ Note: /etc/ssh/ssh_config is for the client and sshd_config is for the SSH daemon.You might want to parse through those two files briefly]

Now, it should let you so scp/ssh/rsync without prompting password

Host_Src# ssh [ip address of Host_Dst]
Host_Src# sftp [ip address of Host_Dst]
Host_Src# scp [ip address of Host_Dst]


Step2: In SLES, apache user is wwwrun. The above SSH tunnel is created for root user. Now we can use the power of SUDOERS to make wwwrun as root.

Host_Src# visudo

wwwrun ALL=(ALL) NOPASSWD:ALL


[username] [all hosts] = [all users] [no password]: [all scripts]
Note: If you use %user, it’s under group privilege

Step3: Since wwwrun is the user without home directory and it doesn’t have any shell; it doesn’t know the location of the command/script files

Host_Src:~ # grep wwwrun /etc/passwd
wwwrun:x:30:8:WWW daemon apache:/var/lib/wwwrun:/bin/false


So, we need to specify full path of the commands for ‘wwwrun’ user. “Which” command gives the complete hard wire location.

Host_Src# which ssh
/usr/bin/ssh


Step4: PHP script created at /srv/www/htdocs/sshdemo.php in Host_Src

<?php
/*
Author: Devendra Shah

*/


$script = '/root/passwordReset.sh'; //Any script file to be executed. I am using simple passwordReset.sh script

$IPadd='169.xxx.1.40'; // IP Address of Host_Dst

//SSH login to the Host_Dst as root user and run PWD command
$output1=exec('sudo -u root /usr/bin/ssh -l root 169.xxx.1.40 pwd');
echo $output1;


//SSH login to the Host_Dst as root user and run the script file located at Host_Dst
$output2 = exec('sudo -u root /usr/bin/ssh -l root '.$IPadd.' bash '.$script.' '.$extension);
echo $output2;


?>