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

标签 php c shell

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

所以我想到的是在 php 中使用 exec()shell_exec() 通过 tmux session 输入命令。问题是 apache 在 www-data 上运行,并且该用户无法创建 tmux session (出于某种原因)。 在互联网上搜索太久后,我找到了 this .一种以 root 身份执行应用程序的方法。即使它是从另一个用户执行的。我试过了,这显然有效,但现在我想通过参数从 php 运行命令。但我不确定这是否会因为注入(inject)而不安全。毕竟它确实需要用户输入。或者只要我在 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 身份运行任何类型的服务器都不是一个好主意。尝试查看是否可以为真正的 super 用户要求保留 root,并使用服务帐户(即非 root 帐户)运行您的应用程序。

关于php - 当 C 使用 system() 和用户输入时,以 root 身份运行 C 是否危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26428759/

相关文章:

php - 使用 PHP 和 MySQL 创建数据库

php - htaccess 在不同的机器上表现不一样

php - 在 Varnish 缓存页面中包含 req.http.referer

检查 EOF 时套接字/文件流上的 C fgetc() 进入无限循环

c - 错误 - <函数声明> 不是指向兼容类型的指针

shell - 从 .zshrc 导出 PYTHONPATH 不起作用

python - 在不创建序列文件的情况下运行 BLAST (bl2seq)

php - 查找两周数字之间所有周的周开始和结束日期

python - 从刷新与未刷新的缓冲区中读取

c - 终止 C 中的递归函数