How can a console application sudo itself under OS X if it needs root privileges? [closed]
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this questionI 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 applicatio开发者_开发知识库ns that require sudo
privileges if it is needed.
It doesn't have to request root access always, only if needed.
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
thesudo
orsu
command and have itself run under UID 0, but only ifsudo
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 systemlaunchd
context. Communicating with that job would causelaunchd
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'sSMJobBless()
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-writtenlaunchd
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.
Yes. For example:
#!/bin/sh
su root
# Do things as root here, if authorized
精彩评论