运行具有不同权限的python

时间:2012-06-17 17:42:19

标签: python linux permissions suid

我正在尝试以其他用户(非root用户)运行python脚本,这也是没有shell的系统用户。我知道我不能直接在脚本上设置suid标志,所以我写了一个C ++包装器。

wrapper.cpp

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>

int main(void)
{
    std::cout << geteuid() << std::endl;

    setgid(getgid());
    setuid(getuid());

    execl("/usr/bin/python2.6", "/usr/bin/python2.6", "test.py", NULL);
}

并设置以下权限

sudo chown NoShellUser:NoShellGroup /path/to/wrapper
sudo chmod 7755 /path/to/wrapper

最后,为了试一试,我有一个python脚本

import sys
import getpass
import os
import pwd
print "VERSION:", sys.version
print "USER:", getpass.getuser(), pwd.getpwuid(os.getuid())
print "EUSER:", pwd.getpwuid(os.geteuid())

如果重要,则使用以下权限

sudo chown NoShellUser:NoShellGroup /path/to/test.py
sudo chmod 7755 /path/to/test.py

现在,当我以用户“test”运行整个事情时,我看到了这一点:

255                                                    # UID of NoShellUser
VERSION: 2.6.8 (unknown, Apr 12 2012, 20:59:36)        # Don't know where that comes from
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)]                # Don't know where that comes from
USER: test pwd.struct_passwd(pw_name='test', pw_passwd='hash', pw_uid=20804, pw_gid=604, pw_gecos='Name Surname', pw_dir='/home/test', pw_shell='/bin/bash')
EUSER: pwd.struct_passwd(pw_name='test', pw_passwd='hash', pw_uid=20804, pw_gid=604, pw_gecos='Name Surname', pw_dir='/home/test', pw_shell='/bin/bash')

正如您所看到的,有效用户仍然是“测试”。有人可以指点我,我做错了什么,因为我已经看了几个例子,他们似乎都或多或少地显示出完全相同的东西?

1 个答案:

答案 0 :(得分:1)

您的包装稍有不妥 - 请尝试使用

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>

int main(void)
{
  std::cout << "Real user " << getuid() << std::endl;
  std::cout << "Effective user " << geteuid() << std::endl;

  setregid(getegid(), getegid());
  setreuid(geteuid(), geteuid());

  std::cout << "Real user " << getuid() << std::endl;
  std::cout << "Effective user " << geteuid() << std::endl;

  execl("/usr/bin/python2.6", "/usr/bin/python2.6", "test.py", NULL);
}

在执行python脚本之前,它将真实有效的用户/组ID设置为有效的组ID。