用用户插入的变量清理exec命令的最佳方法 [英] Best way to sanitize exec command with user inserted variables

查看:82
本文介绍了用用户插入的变量清理exec命令的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个Web接口编写代码,以编码该公司使用的可怕的宣传软件.该软件没有真正的用户界面,要求我们为用户的系统提供腻子访问权限,以使我们的客户甚至可以提取数据.我的Web界面必须运行exec();函数,并且必须传递用户输入的一些变量.

I'm coding a web interface to a horrible piece of propitiatory software our company uses. The software has no real UI and requires us giving putty access to our system for our clients to even pull data. My web interface has to run an exec(); function and it has to pass a few variables the user inputs.

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

现在,我想我也许可以从$command变量中删除所有分号并且是安全的,但是我不确定,这就是为什么我要在下个月开始之前在这里摆弄这个.

Now I assume I might be able to just remove any semicolons from the $command varible and be safe, but I'm not sure and that's why I'm posing this here before we go live next month.

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

What would be the best way to sanitize $command? There are a few special chars that I do need to be in the variables [ ] < > ! # $ .

推荐答案

为此使用PHP具有的功能:

Use the function that PHP has for this purpose:

$cmd = 
     "/usr/bin/do-something " . 
     escapeshellarg($arg1) . 
     ' ' . 
     escapeshellarg($arg2);

您也可以使用escapeshellcmd()

有什么区别?

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

escapeshellarg() ONLY adds ' around the string and then \ before any other ' characters. http://www.php.net/escapeshellarg

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

escapeshellcmd() escapes all shell-sensitive characters ($, \, etc..) but does not add quotes. http://www.php.net/manual/en/function.escapeshellcmd.php

如果您将escapeshellarg()用作QUOTED参数的一部分,则该陷阱了.然后,它变得无用(实际上是在引号中添加了引号).

The gotcha is in the case that you use escapeshellarg() as PART OF A QUOTED parameter. Then it is rendered useless (actually adding quotes to the mix).

通常来说,我们更喜欢使用escapeshellcmd()并添加自己的引号.

Generally speaking, we prefer to use escapeshellcmd() with our own quotes added.

$cmd = 
    "/usr/bin/do-something '" . 
    escapeshellcmd($arg1) . 
    "' '" . 
    escapeshellcmd($arg2) . 
    "'";

安全!

这篇关于用用户插入的变量清理exec命令的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆