c - 在使用 execve() 时寻找匹配的 `' 时出现意外的 EOF

标签 c linux security execve

我尝试通过 execve() 运行多个命令(或使用简单的输出重定向)。

当我放置它时(当然,在我将这个字符串传递给函数之前,我将其分成空格,并将每个空格分开放入 char* []):

"bash -c ' /usr/bin/cat /root/script.sh > /root/script1.sh ' "

到 execve() 函数,我有一个错误:

/usr/bin/cat: -c: line 0: unexpected EOF while looking for matching `''

/usr/bin/cat: -c: line 1: syntax error: unexpected end of file

这是我的建议,使用 exactly execve() 函数(出于安全原因)运行多个 linux 命令(位于 PATH 中的应用程序)

但是这个解决方案并不像我预期的那样有效。

有什么想法可以修复我的解决方案吗?也许我可以使用 execve() 否则,但我不知道如何..

编辑: 添加了简化版(抱歉,由于公司限制,我无法粘贴到原始表格中)源代码:

int foo(const char *cmdline)
{
    char d[] = "bash -c ' /usr/bin/cat /root/script.sh > /root/script1.sh ' ";

    args = strtok(d, " ");
    counter = 0;
    while (args != NULL)
    {
        cmdline_args[counter++] = args;
        args = strtok(NULL, " ");
    }
    cmdline_args[counter] = '\0';

    switch (pid = fork()) {
    case -1:
        ret = -1;
    case 0: // for execve
        status = execve(cmdline_args[0], cmdline_args, env);
        exit(status);
    default: // for parent pid
        if (waitpid(pid, &status, 0) < 0) {
            // in case when waitpid failed
        }
    }
    return ret;
}

最佳答案

由于您的代码是刚刚编写的,我认为它会执行带参数的可执行文件 bash:

[ "bash", "-c", "'", "/usr/bin/cat", "/root/script.sh", ">", "/root/script1.sh", "'", 0]

我猜你反而想瞄准这样的东西:

[ "/bin/bash", "-c", "/usr/bin/cat /root/script.sh >/root/script1.sh", NULL]

bash 二进制文件不太可能很好地响应参数'。当 bash 处理您键入的命令时,它会做很多复杂的工作来处理带引号的字符串的内容,并从中提取实际的预期参数。看起来你可能不得不重复其中的一些工作,如果你真的必须在 cmdline 中处理近乎任意的命令(在这种情况下,我会退后一步并思考'这真的是正确的方法吗做 X?')。

此外,execve 需要二进制文件的完整路径作为其第一个参数;它不搜索 PATH

另外^2:您的标题提到反引号 `,但您的示例代码提到单右引号 ' – 您知道它们非常不同,是吗?

关于c - 在使用 execve() 时寻找匹配的 `' 时出现意外的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868971/

相关文章:

c++ - 如何使用 ffmpeg 将 3840 nb_samples 编码为需要 1024 的编解码器

java - 为在 ubuntu 上使用 RunTime.exec() 运行的 Java 程序提供输入

linux - 将 Oracle 从 Solaris 迁移和升级到 Linux,包括存储过程

algorithm - 在哈希中包含时间戳,但如何比较哈希?

php - MySQLi和PDO哪种方式更安全

c - 简化舍入代码 C

C错误: parameter has incomplete type

php - 我的 PHP 脚本的安全性

c - printf 不打印到屏幕

c++ - 如何修复 OpenGL Superbible 第 6 版书籍提供的 CMake 文件