如何从根目录暂时放弃特权? [英] How to drop privilege temporarily from root?

查看:161
本文介绍了如何从根目录暂时放弃特权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个以root身份运行的守护程序,但是需要与用户调用API,我检查了API代码,它使用getuid()来获取用户.

如果root用户通过setuid()放弃特权,则无法将其还原到root.如果调用seteuid(),API仍将以用户uid=0的身份执行某些操作.

我认为在子进程中访问API和setuid之前,fork应该可以工作,但是即使COW,如果多次调用API也会花费很多.除了使用进程池外,是否可以解决问题?

解决方案

是的!创建单个进程以使用适当的UID调用API,并通过管道,UNIX域套接字或(共享内存) 1 与程序的其余部分进行通信. /p>

我的意思是,只派发一次,让特权用户运行另一个进程.然后根据需要在两者之间建立通信.另外,您可能要考虑使用 dbus ,因为它还与 systemd 完美集成,并且在现代linux上,您希望守护程序与两者很好地交互. /p>

注意:我绝不是这个问题的专家,但这对我来说似乎很简单.您无需为每次调用API都创建一个过程.这是 XY问题(您要解决的实际问题)的一个很好的例子,它与避免fork()多次,因为这样做的想法是错误的解决方案.您只需fork()一次,放弃特权并在没有特权的情况下呆在那里,并根据需要与父进程进行通信.


1 任何适用于您的IPC机制.

I am developing a daemon running as root, but need to call an API with the user, I checked the API codes, it uses getuid() to get the user.

If root user drops privilege by setuid() , it can't be restored to root. If calling seteuid(), the API will still do something as user uid=0.

I think fork before accessing API and setuid in the child process should work, but even if COW , it will cost much if calling API many times. Is it possible to solve the problem except using process pool?

解决方案

Yes! Create a single process to call the API with the appropriate UID and communicate with the rest of the program through a Pipe, a UNIX domain socket or (shared memory)1.

I mean, fork only once and keep the privileged user running another process. Then create communication between the two if needed and as needed. Also, you might want to consider using dbus since it also integrates perfectly with systemd and on modern linux you want your daemon to interact nicely with both.

Note: I am by no means an expert on the subject, but this is a simple idea that seems clear to me. You don't need to create a process for every call to the API. This is a good example of the XY problem, the real problem that you want to solve, has nothing to do with avoiding to fork() multiple times because the idea of doing that is the wrong solution. You only need to fork() once, drop privileges and stay there without privileges, communicating with the parent process if/as needed.


1Any IPC mechanism that works for you.

这篇关于如何从根目录暂时放弃特权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆