当使用system()和用户输入时,以root身份运行C是否危险


Is running a C as root dangerous when it uses system() and a user input?

基本上我想要实现的是通过php在java控制台中运行命令。我想做这件事的方式可能太牵强了,所以如果有更简单的方法,请告诉我。

因此,我想到的是在php中使用exec()shell_exec()通过tmux会话输入命令。问题是apache运行在www数据上,用户无法创建tmux会话(出于某种原因)。在网上搜索了太久之后,我发现了这个。以root身份执行应用程序的一种方式。即使它是从另一个用户执行的。我试过了,这显然有效,但现在我想通过参数从php运行命令。但我不确定这是否会因为注射而不安全。毕竟,它确实需要用户输入。或者,只要我在php中使用escapeshellarg()escapeshellcmd(),我就不必担心这个问题吗?

提前感谢您的帮助:)

在root(通过sudo)执行的脚本中,我放入以下内容来检查传递的参数。我怀疑您必须以相同的方式检查输入的每一行,然后检查每一行上的命令,以确定是否要执行它。

如果您的服务器不是以root用户身份运行,而是以其他"常规"用户身份运行的话,会安全得多。所以我同意这是个坏主意,但如果我必须这样做,那么我会使用这个:

# Check to make sure the parameters do not have special characters
security_check () {
  # echo does not execute the contents of "$@" provided it is inside
  # double quotes.
  SC_PARMS1="`echo '"$@'" | tr '"'''`<>|'" '"xxxx'"`"
  SC_PARMS2="`echo '"$@'" | tr '"'''`<>|'" '"yyyy'"`"
  # Can't use "$@" in if test as it executes the contents, hence we
  # must compare 2 different converted strings.
  if [ "$SC_PARMS1" != "$SC_PARMS2" ]; then
    echo "`uname -n`: Security abort in: $0 $@"
    return 1
  fi
  unset SC_PARMS1 SC_PARMS2
  return 0
}
while read line ; do
    security_check "$line"
    if [ $? = 0 ]; then
        echo "We could execute $line"
        # Now we need to check the commands we allow
        if [ "$line" = "ls" ]; then
            # This test is very rudimentary, you might need to do a set -- $line and
            # examine more than just the command ($1 at that point)
            eval $line
        fi
    fi
done

以root身份运行任何类型的服务器都不是一个好主意。试着看看是否可以为真正的超级用户需求保留root,并使用服务帐户(即非root帐户)运行您的应用程序。

(括号中的此行仅满足最少30个字符的要求。)

这是安全的

只要它能正确逃脱。这使得它听起来比正确地转义输入并确保其100%安全要容易得多。

尽管你确定所有这些访问都是需要的吗?如果攻击者想以某种方式进入,你应该限制他们的访问权限。拥有root访问权限比只拥有用户帐户要糟糕得多