【问题标题】:Executing a Python command with a setuid/setgid wrapper使用 setuid/setgid 包装器执行 Python 命令
【发布时间】:2016-12-05 20:24:40
【问题描述】:

我想使用 setuid/setgid 位提供的权限执行以下 Python 脚本:

#!/usr/bin/env python3
from mypackage.cli import main as cli_main
cli_main()

但是:我想直接从 C 包装器执行命令,而不需要中间 Python 脚本文件。

我已尝试使用execve 执行此操作,如下所示:

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

const char *ENV = "/usr/bin/env";
const char *ENV_ARGS[] = { "python3", "-c", "from mypackage.cli import main as cli_main; cli_main()" };
const int NUM_ENV_ARGS = 3;

int main(int argc, char *argv[], char *envp[]) {
    int total_num_args = (argc - 1) + NUM_ENV_ARGS + 1;

    // Create an array of strings to hold the final arg list.
    // No need to free the malloc'ed memory as it will be freed if execve succeeds,
    // or when the program exits if execve fails.
    char **final_args = (char **)malloc(total_num_args * sizeof(char *));
    if (final_args == NULL) {
        return 1;
    }

    // Copy the invocation and the arguments to this program into the final arg list.
    memcpy(final_args, ENV_ARGS, NUM_ENV_ARGS * sizeof(char *));
    memcpy(final_args + NUM_ENV_ARGS, argv + 1, (argc - 1) * sizeof(char *));
    final_args[total_num_args - 1] = NULL;

    return execve(ENV, final_args, envp);
}

但是当我以./mycli foo bar 运行编译程序时出现以下错误:

python3: illegal option -- c
usage: env [-iv] [-P utilpath] [-S string] [-u name]
           [name=value ...] [utility [argument ...]]

我怎样才能做到这一点?

【问题讨论】:

  • ./mycli foo bar。但是,在没有任何参数的情况下也会发生同样的错误。

标签: python c setuid execve


【解决方案1】:

您正在错误地构造参数数组。它应该与执行程序的argv 数组完全对应,包括第 0th 元素指定程序的名称,在这种情况下通常是“env”或“/usr/垃圾箱/环境”。因为您跳过了“env”,env 将“python3”解释为 它自己的 名称,如错误消息所示。该消息来自 env,而不是 Python。

【讨论】:

    【解决方案2】:

    您没有运行python3 命令。您正在运行 env 命令。 ENV 变量应该包含 /usr/bin/python3,或者任何指向 python3 的路径。

    【讨论】:

    • 环境变量从调用者传递到execve 调用,因此env 获得的变量与我直接从命令行调用它时所拥有的变量相同。
    • @DanielGibbs 不,那些环境变量在envp 中。无需致电env
    • 那么我会做些什么来让它工作呢?我想使用env,因为我无法保证python3 可执行文件的位置。
    • @DanielGibbs 如果您知道python3 在路径上,只需使用const char *ENV = "python3"。然后使用搜索路径的execvp,而不是execve
    • "其他函数从调用进程中的外部变量 environ 获取新进程映像的环境。"那一定是我在手册页中遗漏的部分。
    猜你喜欢
    • 2014-08-23
    • 2010-12-02
    • 2017-02-03
    • 2020-05-01
    • 2017-02-15
    • 1970-01-01
    • 2020-10-25
    • 2020-05-05
    • 2017-07-30
    相关资源
    最近更新 更多