How can a console application use sudo under OS X if it needs root privileges?

I am wondering if it is possible for a command line application to request root access, such as trying to invoke itself with sudo

.

I am looking for a solution that allows me to write applications that require privileges sudo

if needed.

It shouldn't always ask for root access, only when needed.

+2


source to share


2 answers


Parameters:

  • it could setuid(0)

    , but only if it was already called by root and therefore has a real UID of 0 and the effective UID of someone else.
  • it could try the exec

    command, sudo

    or it could su

    run itself under UID 0, but only if sudo

    configured to allow it (which usually requires the user to send authentication, as would an authorization check).
  • it can try to start a fresh copy of itself through AuthorizationExecWithPrivileges()

    , but this again requires the user to submit authn.
  • it could be set with a job launchd

    that it can interact with in the context of the system launchd

    . Communicating with this job would launchd

    trigger to invoke it, and apparently it is configured to run as root. This now requires the work to be already deployed, either through the installer (in this case the user authenticated) or through the API Management SMJobBless()

    API (again, the user will need authentication to approve this).
  • it can use another poorly written job launchd

    to execute that job with UID 0. As noted, this is due to a poor job record launchd

    .


So, whenever possible, using a number of options, but all reliable ones require that the user is authenticated and that the tool has already been deployed so that it can run in the root context. I've actually written a whole book on this stuff ... see in particular chapter 6 of Professional Cocoa Application Security .

Note that all parameters except setuid

(which I do not recommend you use) were actually included fork()

to create a separate process, be it the calling process or launchd

. This means that you actually have two separate executables: one that the user interacts with and one that performs privileged tasks. This is a better design than using all the features in one application, which is why I recommend this approach.

+5


source


Yes. For example:



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

      

0


source







All Articles