使用用户插入的变量清理exec命令的最佳方法

The*_*nja 15 php exec sanitize

我正在为我们公司使用的一个可怕的软件编写一个Web界面.该软件没有真正的用户界面,需要我们为我们的客户提供putty访问我们的系统甚至提取数据.我的Web界面必须运行一个exec();函数,它必须传递用户输入的一些变量.

$command = "report-call '$type' '$study' '$server' '$tag' '$specopt1' '$specopt2' '$specopt3' '$specopt4'";
$last_line = exec($command, $output, $returnvalue); 
Run Code Online (Sandbox Code Playgroud)

现在我假设我可能只是从$command变量中删除任何分号并且是安全的,但我不确定,这就是为什么我在下个月上线之前在这里提出这个问题.

什么是最好的消毒方法$command?我确实需要在变量中使用一些特殊的字符 [ ] < > ! # $.

gah*_*ooa 21

使用PHP具有的功能:

$cmd = 
     "/usr/bin/do-something " . 
     escapeshellarg($arg1) . 
     ' ' . 
     escapeshellarg($arg2);
Run Code Online (Sandbox Code Playgroud)

你也可以使用 escapeshellcmd()

有什么不同?

escapeshellarg()只在字符串周围添加'然后在任何其他'字符之前添加\. http://www.php.net/escapeshellarg

escapeshellcmd()转义所有对shell敏感的字符($,\等等),但不添加引号. http://www.php.net/manual/en/function.escapeshellcmd.php

在您使用escapeshellarg()作为QUOTED参数的部分的情况下,问题就在于此.然后它变得无用(实际上为混音添加引号).

一般来说,我们更喜欢使用escapeshellcmd()我们自己的报价添加.

$cmd = 
    "/usr/bin/do-something '" . 
    escapeshellcmd($arg1) . 
    "' '" . 
    escapeshellcmd($arg2) . 
    "'";
Run Code Online (Sandbox Code Playgroud)

注意安全!

  • 删除了我的答案,因为显然我们在同一时间打字,但你提供了不错的例子.手册链接:http://us.php.net/manual/en/function.escapeshellarg.php,http://us.php.net/manual/en/function.escapeshellcmd.php (3认同)
  • 请注意,`escapeshellcmd()` 实际上并没有转义 '!',所以如果您在例如 Bash 中运行该命令,您仍然容易受到命令替换的影响(例如,`this-is-a-test-!467 ` 其中 `!467` 将被替换为 shell 历史记录中第 467 号的任何内容)。`escapeshellarg()` 缓解了这种情况。 (2认同)