1

I am passing dynamic shell commands over SSH to servers with PHP using the ssh2 library. The command I am passing is (note this is just an example, the commands are dynamic and user generated).

$command = 'ls -al
free -m';

Notice the newline, this is required, since users can type full bash scripts with newlines and tabs. Then, I do the following to build the actual command to execute with the ssh2 library:

$command = str_replace("'", "\'", $command);
$command = 'echo $\'' . $command . '\' | bash';

Which results in the final command of:

echo $'ls -al
free -m' | bash

The above command executes fine at the shell directly, but when I execute it from PHP using ssh2, and I getting:

ls: invalid option --  
Try `ls --help' for more information.

So I thought, ok there must be some special characters or the dollar sign is not being escaped, so I did:

  print_r(bin2hex($command));

Which results in:

 6563686f2024276c73202d616c0d0a66726565202d6d27207c2062617368

Converting the hex into ascii returns the correct command (exactly as above) though.

Any idea what could be causing this?

Justin
  • 42,716
  • 77
  • 201
  • 296

1 Answers1

0

That error comes from bash, not PHP.

When I try your command in a shell I get the same error.

But why are you using such a convoluted way of running bash?

Instead use proc_open(), with bash as the command, then feed it the user input in the stdin filehandle.

If you need an example of how to use it: https://stackoverflow.com/a/2390755/664364

PS. I hope you know what you are doing allowing users to run arbitrary commands as the webserver user!

Community
  • 1
  • 1
Ariel
  • 25,995
  • 5
  • 59
  • 69
  • It is a long story to explain why it is setup like this. Security aside. Really, when you copy and paste the contents of `$command` you get a bash error? I don't in CentOS. – Justin Sep 13 '12 at 01:16
  • I do, yes. Although the error is different. I get `ls: invalid option -- 'e'` – Ariel Sep 13 '12 at 01:17
  • I have edited the posted, please read the top to see a better explanation. – Justin Sep 13 '12 at 01:21
  • @Justin Your edit didn't change anything - I still think this is a bash error, and not a PHP one. Try using proc_open instead. Test it! Add a semicolon after the ls and watch it work. – Ariel Sep 13 '12 at 01:51