Skip to main content
 首页 » 编程设计

python之带有嵌入式 Python 的 C 程序 : How to restrict process to not open files nor sockets

2024年10月25日12telwanggs

我喜欢禁止我的 C 程序某些权利、权限或能力,例如打开任何文件(stdin、stdout、stderr 除外)或任何套接字,理想情况下即使以 root 身份运行。原因是,该程序嵌入了 Python 解释器,可能会运行不受信任的代码。简化版:

int main(int argc, char** argv) 
{ 
    /* TODO: drop all rights/permissions/capabilites 
       to open files or sockets here! */ 
 
    Py_Initialize(); 
    PyRun_SimpleString(argv[1]); 
    Py_Finalize(); 
} 

这必须在 Linux 3.2 上使用 Python 2.6。有什么想法吗?

请您参考如下方法:

也许我自己找到了答案。非常需要评论!

我正在尝试使用 seccomp 库来禁止除某些系统调用之外的所有系统调用。

它似乎有效,即在我的天真测试中,我可以从标准输入读取,写入标准输出,但无法通过 Python 打开文件。

#include <stdio.h> 
 
#include <seccomp.h> 
 
#include <python2.7/Python.h> 
 
#define ERR_EXIT(err) do { \ 
    fprintf(stderr, "%s near line %d\n", strerror(-err), __LINE__); \ 
    exit(-1); } while (0); 
 
int main(int argc, char** argv) 
{ 
    int i; 
    scmp_filter_ctx ctx; 
    int err; 
 
    Py_Initialize(); 
 
    /* return illegal calls with error */ 
    if (!(ctx = seccomp_init(SCMP_ACT_ERRNO(1)))) { 
        ERR_EXIT(1); 
    } 
    /* allow write, but only to stdout */ 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 
                    1, SCMP_A0(SCMP_CMP_EQ, STDOUT_FILENO)))) { 
        ERR_EXIT(err); 
    } 
    /* allow read, but only from stdin */ 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 
                    1, SCMP_A0(SCMP_CMP_EQ, STDIN_FILENO)))) { 
        ERR_EXIT(err); 
    } 
    /* brk, exit, exit_group, and rt_sigaction are needed by Python */ 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0))) { 
        ERR_EXIT(err); 
    } 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0))) { 
        ERR_EXIT(err); 
    } 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0))) { 
        ERR_EXIT(err); 
    } 
    if ((err = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigaction), 0))) { 
        ERR_EXIT(err); 
    } 
 
    if ((err = seccomp_load(ctx))) { 
        ERR_EXIT(err); 
    } 
 
    for (i = 1; i < argc; i++) { 
        PyRun_SimpleString(argv[i]); 
    } 
 
    Py_Finalize(); 
 
    return 0; 
} 

我非常感谢对这种方法的任何批评,谢谢!