How can a console application sudo itself under OS X if it needs root privileges? [closed]

僤鯓⒐⒋嵵緔 提交于 2020-01-04 06:21:07

问题


I am wondering if it is possible for a command line application to request root access, like trying to call itself with sudo.

I am looking for a solution that would allow to write applications that require sudo privileges if it is needed.

It doesn't have to request root access always, only if needed.


回答1:


The options:

  • it could setuid(0), but only if it already has been invoked by root and so has a real UID of 0 and an effective UID of somebody else.
  • it could try to exec the sudo or su command and have itself run under UID 0, but only if sudo is configured to allow that (which normally requires that the user submit to authentication, as there will be an authorization check).
  • it could try to launch a new copy of itself via AuthorizationExecWithPrivileges(), but this again requires that the user submit to authn.
  • it could have been installed with a launchd job that it can communicate with in the system launchd context. Communicating with that job would cause launchd to invoke it, and presumably it's configured to run under the root user. Now for this to come about, the job needs to have already been deployed: either via an installer (in which case the user authenticated) or via the Service Management framework's SMJobBless() API (again, the user will need authentication to approve that).
  • it could make use of someone else's badly-written launchd job to have that job execute itself with UID 0. As noted, this involves having a badly-written launchd job knocking around.

So essentially it is possible, through a number of options, but all of the reliable ones require that the user authenticate and that the tool already be deployed in such a way as it can run in the root context. I actually wrote a whole book about this stuff...see particularly Chapter 6 of Professional Cocoa Application Security.

Notice that all of the options except setuid (which I don't recommend you use) actually involved a fork() to create a separate process, whether by the calling process or by launchd. That means you can actually have two separate executables: one that the user interacts with, and one that performs privileged tasks. That's a better design than putting all of the functionality in one application so I'd recommend that approach.




回答2:


Yes. For example:

#!/bin/sh
su root
# Do things as root here, if authorized


来源:https://stackoverflow.com/questions/6161602/how-can-a-console-application-sudo-itself-under-os-x-if-it-needs-root-privilege

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