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

How does execve prevents vulnerabilities compared to system command

本文关键字:何防止 漏洞 execve 系统命令      更新时间:2023-10-16

我指的是这个链接,
基本上,考虑输入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的参数。所以我们将得到一个等于"0"的返回值;无效参数";。我的理解正确吗?还是有什么比我的理解更深刻的东西我错过了?

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

是的,你的理解是正确的