我喜欢禁止我的 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 库来禁止除某些系统调用之外的所有系统调用。
它似乎有效,即在我的天真的测试中,我可以从 stdin 读取,写入 stdout,但无法通过 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;
}
我非常感谢对这种方法的任何批评,谢谢!
关于python - 嵌入Python的C程序: How to restrict process to not open files nor sockets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501782/