3

I can't decide whether I'm being overly paranoid here, but if I'm running a PHP script from a commandline and that script echo's out user defined content, do I need to escape it?

For example, would this be potentially dangerous or would the text literally just echo out as plain text?

$test = 'shutdown -h now';
echo $test;

If I do need to escape, is it the escapeshellarg() function I want?

Ric
  • 458
  • 1
  • 7
  • 23
  • 1
    Yes. You should, if you pass user defined params to `exec()` or `shell_exec()`. – BlitZ Sep 15 '13 at 11:08
  • 1
    The question is explicitly stated to be about `echoing out user defined content`, nothing about any `exec()` or such. – Cthulhu Sep 15 '13 at 11:15

3 Answers3

3

The shell interpretes commands from stdin but you are writing to stdout. So everything is fine

However, to prevent you from accidently copy pasting them into a terminal it is never a bad idea to escape them

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Thanks hek2mgl, that makes sense =). I guess I'm just overthinking things again! – Ric Sep 15 '13 at 11:21
  • 1
    @Ric np :) Also note the answer from ComFreek. Some sequences could break your terminal output – hek2mgl Sep 15 '13 at 11:22
3

I do not fully agree with the other answers.

It is right that you write to stdout, so the input won't be interpreted as commands, but some special control sequences can invoke some shell-related behaviour. See here, for example.

These cannot call other programs or commands, but they can annoy the user (he has to type reset for resseting the shell).

Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • Interesting... how would you protect against this, ComFreek? exec('reset'); at the end perhaps? – Ric Sep 15 '13 at 11:26
  • @Ric `exec('reset');` sounds nice! I currently see no other way if you are outputting random data (beside from manually escaping them) – hek2mgl Sep 15 '13 at 11:35
  • @Ric I think escaping is not as complex as one might think. These characters should be very easy to catch in the string stream. I am not an expert on this topic, so I cannot give any further advices. This link might help you: http://stackoverflow.com/questions/6534556/how-do-we-remove-and-all-of-the-escape-sequences-in-a-file-using-linux-shell – ComFreek Sep 15 '13 at 12:13
  • @hek2mgl Doesn't `reset` reset the whole terminal? The output would be cleared then. – ComFreek Sep 15 '13 at 12:13
0

It should not be dangerous. User can't invoke any command this way. Of course if you are not using exec() or similar function in between. Please note that passing any argument to phpcli from command line is dangerous. Because this argument may contain "`", that executes the command in shell to get a result.

Flash Thunder
  • 11,672
  • 8
  • 47
  • 91