C++ 如何以编程方式获得root权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2483755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically gain root privileges?
提问by ereOn
I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).
我正在编写一些软件(在 C++ 中,用于 Linux/Mac OSX),它以非特权用户身份运行,但在某些时候需要 root 权限(以创建新的虚拟设备)。
Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.
以 root 身份运行这个程序不是一个选项(主要是为了安全问题),我需要知道“真实”用户的身份(uid)。
Is there a way to mimic the "sudo" command behavior (ask for user password) to temporarily gain root privileges and perform the particular task ? If so, which functions would I use ?
有没有办法模仿“sudo”命令行为(询问用户密码)来临时获得 root 权限并执行特定任务?如果是这样,我会使用哪些功能?
Thank you very much for your help !
非常感谢您的帮助 !
采纳答案by phihag
Original answer
原答案
You might consider the setuid switch on the executable itself. Wikipedia has an articleon it which even shows you the difference between geteuid()
and getuid()
quite effectively, the former being for finding out who you're "emulating" and the latter for who you "are". The sudo process, for example, geteuid should return 0 (root) and getuid your user's id, however, its sub-processes do truly run as root (you can verify this with sudo id -u -r
).
您可以考虑在可执行文件本身上使用 setuid 开关。维基百科有一篇关于它的文章,它甚至向你展示了两者之间的区别,geteuid()
并且getuid()
非常有效,前者是为了找出你在“模仿”谁,而后者是为了你“是谁”。例如,sudo 进程 geteuid 应该返回 0(root)并 getuid 您的用户 ID,但是,它的子进程确实以 root 身份运行(您可以使用 验证这一点sudo id -u -r
)。
I don't think there's a way to easily programmatically gain root access - after all, applying the principle of least privilege, why would you need to? Common practise is to run only limited parts of code with elevated privileges. A lot of daemons etc are also set up under modern systems to run as their own user with most of the privileges they need. It's only for very specific operations (mounting etc) that root privileges are truly needed.
我不认为有一种方法可以轻松地以编程方式获得 root 访问权限 - 毕竟,应用最小特权原则,为什么需要?通常的做法是仅运行具有提升权限的代码的有限部分。许多守护进程等也在现代系统下设置为以他们自己的用户身份运行,并拥有他们所需的大部分权限。只有非常具体的操作(挂载等)才真正需要 root 权限。
2013 update
2013年更新
My original answer stands (although my 2013 self might make a better job of it than my 2010 one), but if you are designing an application that requires root access, you may want to consider exactly what sort of root access is needed and consider the use of POSIX Capabilities(man page). These are different to capability-based securityas implemented in L4 et al. POSIX capabilities allow your application to be granted a subset of root's powers. For example CAP_SYS_MODULE
will allow you to insert kernel modules, but give you no other root powers. This is in use in distributions e.g. Fedora has a feature to completely remove setuid binarieswith indiscriminate root access.
我最初的答案是成立的(尽管我 2013 年的自己可能比 2010 年的自己做得更好),但是如果您正在设计一个需要 root 访问权限的应用程序,您可能需要确切地考虑需要什么样的 root 访问权限并考虑POSIX 功能的使用(手册页)。这些与L4 等人实现的基于能力的安全不同。POSIX 功能允许您的应用程序被授予根权限的子集。例如,CAP_SYS_MODULE
将允许您插入内核模块,但不会给您其他根权限。这是在发行版中使用的,例如Fedora 具有完全删除具有不加选择的 root 访问权限的setuid 二进制文件的功能。
This matters because as a programmer, your code is obviously perfect! But, the libraries on which you depend (sigh, if only you'd written them!) might have vulnerabilities in them. Using capabilities, you can limit the use of this exploit, and save yourself and your company from security-related scrutiny. This makes everyone happier.
这很重要,因为作为程序员,您的代码显然是完美的!但是,您所依赖的库(叹息,如果您已经编写了它们!)可能存在漏洞。使用功能,您可以限制此漏洞的使用,并使您自己和您的公司免于与安全相关的。这让每个人都更快乐。
回答by phihag
If you need root privileges every time, the best thing is to start your program as root and drop them (in a subprocess) with setuidand setgid. That's what apache does when it needs to bind to the restricted port 80.
如果您每次都需要 root 权限,最好的办法是以 root 身份启动您的程序并使用setuid和setgid删除它们(在子进程中)。这就是 apache 在需要绑定到受限端口 80 时所做的事情。
If gaining root rights is the exception instead of the rule and the program is run interactively, another way is to write a program add_interface and execute
如果获得root权限是例外而不是规则并且程序是交互运行的,另一种方法是编写程序add_interface并执行
sudo add_interface args
and let sudo handle authentication for you. Instead of sudo, you may want to use a graphical frontend like gksu, gksudo, kdesu, or kdesudo. I wouldn't try to implement secure password input myself; it can be a tricky problem and you'll probably leave gaping security holes and functionality problems (Do you support fingerprint readers?).
并让 sudo 为您处理身份验证。除了 sudo,您可能希望使用图形前端,如 gksu、gksudo、kdesu 或 kdesudo。我不会尝试自己实现安全密码输入;这可能是一个棘手的问题,您可能会留下巨大的安全漏洞和功能问题(您支持指纹读取器吗?)。
Another alternative is polkit, previously called PolicyKit.
另一种选择是polkit,以前称为 PolicyKit。
回答by kdgregory
You can't gain root privileges, you must start out with them and reduce your privileges as needed. The usual way that you do this is to install the program with the "setuid" bit set: this runs the program with the effective userid of the file owner. If you run ls -l
on sudo
, you'll see that it is installed that way:
您无法获得 root 权限,您必须从它们开始并根据需要减少您的权限。执行此操作的常用方法是在设置“setuid”位的情况下安装程序:这将使用文件所有者的有效用户 ID 运行程序。如果你运行ls -l
on sudo
,你会看到它是这样安装的:
-rwsr-xr-x 2 root root 123504 2010-02-25 18:22 /usr/bin/sudo
While your program is running with root privileges, you can call the setuid(2)
system call to change your effective userid to some non-privileged user. I believe (but haven't tried this) that you could install your program as root with the setuid bit on, immediately reduce privilege, and then restore privilege as needed (it's possible, however, that once you lower your privilege you won't be able to restore it).
当您的程序以 root 权限运行时,您可以调用setuid(2)
系统调用将您的有效用户 ID 更改为某些非特权用户。我相信(但还没有尝试过)您可以在 setuid 位打开的情况下以 root 用户身份安装程序,立即减少特权,然后根据需要恢复特权(但是,一旦您降低特权,您就不会可以恢复)。
A better solution is to break out the piece of your program that needs to run as root, and install it with the setuid bit turned on. You will, of course, need to take reasonable precautions that it can't be invoked outside of your master program.
更好的解决方案是拆分需要以 root 身份运行的程序部分,并在打开 setuid 位的情况下安装它。当然,您需要采取合理的预防措施,不能在主程序之外调用它。
回答by Joshua
Normally this is done by making your binary suid-root.
通常这是通过制作二进制 suid-root 来完成的。
One way of managing this so that attacks against your program are hard is to minimize the code that runs as root like so:
管理这种情况以便对您的程序进行攻击的一种方法是最小化以 root 身份运行的代码,如下所示:
int privileged_server(int argc, char **argv);
int unprivileged_client(int argc, char **argv, int comlink);
int main(int argc, char **argv) {
int sockets[2];
pid_t child;
socketpair(AF_INET, SOCK_STREAM, 0); /* or is it AF_UNIX? */
child = fork();
if (child < 0) {
perror("fork");
exit(3);
} elseif (child == 0) {
close(sockets[0]);
dup2(sockets[1], 0);
close(sockets[1]);
dup2(0, 1);
dup2(0, 2); /* or not */
_exit(privileged_server(argc, argv));
} else {
close(sockets[1]);
int rtn;
setuid(getuid());
rtn = unprivileged_client(argc, argv, sockets[0]);
wait(child);
return rtn;
}
}
Now the unprivileged code talks to the privileged code via the fd comlink (which is a connected socket). The corresponding privileged code uses stdin/stdout as its end of the comlink.
现在非特权代码通过 fd comlink(这是一个连接的套接字)与特权代码对话。相应的特权代码使用 stdin/stdout 作为其通信链接的结尾。
The privileged code needs to verify the security of every operation it needs to do but as this code is small compared to the unprivileged code this should be reasonably easy.
特权代码需要验证它需要执行的每个操作的安全性,但由于此代码与非特权代码相比较小,因此应该相当容易。
回答by Frerich Raabe
On OS X, you can use the AuthorizationExecuteWithPrivileges
function. The page on Authorization Services Taskshas some elaborate discussion of this (and related) functions.
在 OS X 上,您可以使用该AuthorizationExecuteWithPrivileges
功能。授权服务任务页面对此(和相关)功能进行了一些详细的讨论。
Here's a bit of C++ code to execute a program with administrator privileges:
下面是一些 C++ 代码,用于以管理员权限执行程序:
static bool execute(const std::string &program, const std::vector<std::string> &arguments)
{
AuthorizationRef ref;
if (AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &ref) != errAuthorizationSuccess) {
return false;
}
AuthorizationItem item = {
kAuthorizationRightExecute, 0, 0, 0
};
AuthorizationRights rights = { 1, &item };
const AuthorizationFlags flags = kAuthorizationFlagDefaults
| kAuthorizationFlagInteractionAllowed
| kAuthorizationFlagPreAuthorize
| kAuthorizationFlagExtendRights;
if (AuthorizationCopyRights(ref, &rights, kAuthorizationEmptyEnvironment, flags, 0) != errAuthorizationSuccess) {
AuthorizationFree(ref, kAuthorizationFlagDestroyRights);
return false;
}
std::vector<char*> args;
for (std::vector<std::string>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
args.push_back(it->c_str());
}
args.push_back(0);
OSStatus status = AuthorizationExecuteWithPrivileges(ref, program.c_str(), kAuthorizationFlagDefaults, &args[0], 0);
AuthorizationFree(ref, kAuthorizationFlagDestroyRights);
return status == errAuthorizationSuccess;
}
回答by themoondothshine
You might want to take a look at these APIs:
您可能想看看这些 API:
setuid, seteuid, setgid, setegid, ...
They're defined in the header <unistd.h>
in Linux systems (don't know much about MAC, but you should have a similar header there too).
它们是<unistd.h>
在 Linux 系统的头文件中定义的(对 MAC 了解不多,但你也应该在那里有一个类似的头文件)。
One problem that I can see is that the process must have sufficient privileges to change its user-/group- IDs. Otherwise calls to the above functions will result in an error with errorno
set to EPERM
.
我可以看到的一个问题是该进程必须具有足够的权限才能更改其用户/组 ID。否则对上述函数的调用将导致errorno
set to错误EPERM
。
I would suggest that you run your program as the root
user, change effective user ID (using seteuid
) to an underprivileged user at the very beginning. Then, whenever you need to elevate permissions, prompt for a password then use seteuid
again to revert to the root
user.
我建议您以root
用户身份运行您的程序,一开始就将有效用户 ID(使用seteuid
)更改为低权限用户。然后,每当您需要提升权限时,提示输入密码,然后seteuid
再次使用以恢复root
用户。
回答by Gerco Dries
You can try launching the command to create the virtual device (including sudo) through a background shell. Ask for the users password in a dialog of your own and pipe that into the shell when sudo asks for it. There are other solutions like using gksu, but those are not guaranteed to be available on every machine.
您可以尝试通过后台shell启动命令来创建虚拟设备(包括sudo)。在您自己的对话框中询问用户密码,并在 sudo 要求时将其输入到 shell 中。还有其他解决方案,例如使用 gksu,但不能保证在每台机器上都可用。
You don't run your entire program as root, but only the small part of it that needs root. You should spawn a separate process for that and sudo may be of assistance to you.
您不会以 root 身份运行整个程序,而只是其中一小部分需要 root 身份。您应该为此创建一个单独的进程,而 sudo 可能对您有所帮助。