与系统命令相比,execve如何防止漏洞

时间:2014-10-27 09:01:43

标签: c++ linux security

我指的是this链接,
基本上,考虑输入happy'; useradd 'attacker,安全建议区分兼容和不兼容的代码 -

非投诉代码

#include <string.h>
#include <stdlib.h>

enum { BUFFERSIZE = 512 };

void func(const char *input) {
  char cmdbuf[BUFFERSIZE];
  int len_wanted = snprintf(cmdbuf, BUFFERSIZE,
                            "any_cmd '%s'", input);
  if (len_wanted >= BUFFERSIZE) {
    /* Handle error */
  } else if (len_wanted < 0) {
    /* Handle error */
  } else if (system(cmdbuf) == -1) {
    /* Handle error */
  }
}

合规代码

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void func(char *input) {
  pid_t pid;
  int status;
  pid_t ret;
  char *const args[3] = {"any_exe", input, NULL};
  char **env;
  extern char **environ;

  /* ... Sanitize arguments ... */

  pid = fork();
  if (pid == -1) {
    /* Handle error */
  } else if (pid != 0) {
    while ((ret = waitpid(pid, &status, 0)) == -1) {
      if (errno != EINTR) {
        /* Handle error */
        break;
      }
    }
    if ((ret != -1) &&
      (!WIFEXITED(status) || !WEXITSTATUS(status)) ) {
      /* Report unexpected child status */
    }
  } else {
    /* ... Initialize env as a sanitized copy of environ ... */
    if (execve("/usr/bin/any_cmd", args, env) == -1) {
      /* Handle error */
      _Exit(127);
    }
  }
}

假设我们将相同的输入传递给具有相同权限的函数,即由root等运行等,第二种解决方案如何确保命令注入攻击被排斥?

我的唯一猜测是,execve会使用any_cmd刷新二进制图片,并使用输入happy'; useradd 'attacker作为any_cmd的参数。所以我们将得到一个等于“无效参数”的返回值。我的理解是对的吗?或者是否有比我理解的更深刻的东西?

1 个答案:

答案 0 :(得分:1)

主要区别在于使用system函数可以启动shell可以执行的任何操作,因此您基本上可以使用多个命令进行shell注入。而execve首先指定要执行的特定二进制文件,因此您非常确定只执行了一个命令(除非您execve一个shell ...)。此外,由于您提供了execve的完整路径,因此您可以根据修改HOME或当前工作目录来避免黑客攻击。

所以是的,你的理解是正确的