Access /Private/etc with c

我与影子孤独终老i 提交于 2020-01-12 10:30:11

问题


this might be a simple question, but how do I "request" system / root priviliges from the user in a c console application. I need to write to /Private/etc but i can't. This is for mac / unix.

I've seen it being used in other console commands e.g. when you run the following command: "sudo /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder", Terminal asks you for your Password. How do I do this?

thanks, JNK


回答1:


There isn't any system call which will let a process obtain root privileges. You might expect seteuid to work this way, but it can only be used by processes with root processes (unprivileged processes can only set the euid equal to the uid).

sudo is special because its executable file has setuid permissions. This means that when sudo is run, it runs as the user that owns it (root) rather than the user executing it. sudo can verify you have root access by checking your password and reading a configuration file. If the check succeeds, it calls fork and execve to execute the command you requested.

To obtain root privileges within an unprivileged application, you would have to jump through some hoops. You can use fork/execve to call sudo for your own command. Once authenticated, you would have a privileged child process. You could pass a special argument or environment variable so the child process can jump to code that is intended to be privileged. The parent process would just wait for the child process to complete.




回答2:


The way to do what you want on the Mac is write a "factored application", consisting of the part that's run by a user and the part that does the privileged task. Install the privileged part in the system launchd domain, and get the user tool to call on it for the work that needs special permissions.

You need to ensure that only authorised use of the privileged helper can occur, and you do this using Authorization Services. In the user tool, you acquire a "right", which you then convert into an external form and pass to the helper. The helper tool should verify that it correctly has the right before it tries to do the privileged work.

The other option is to write the whole tool to fail gracefully (which you have to do in either case), and ask users to run it via sudo if they need privileged access. That's how the rest of UNIX works.




回答3:


For UNIX systems, you'll need to have the setuid flag on your program, and it should check /etc/passwd and /etc/shadow for valid credentials. I believe the crypt(3) function is used for password hashing. Not sure about Mac.



来源:https://stackoverflow.com/questions/4556186/access-private-etc-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!