Hedge
Hedge

Reputation: 16748

Re-Use Authorization to use with AuthorizationExecuteWithPrivileges in another program execution?

I have a CLI-tool which creates an authorization and then uses it execute a command authorized. I need to call this CLI-tool a number of times in a row.

How do I re-use the authorization given when I called the tool for the first time? This is my authorization-code:

AuthorizationRef authorizationRef;
status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
AuthorizationExecuteWithPrivileges(authorizationRef, "/bin/rm", kAuthorizationFlagDefaults, NULL  , NULL);

Upvotes: 1

Views: 726

Answers (2)

TheDarkKnight
TheDarkKnight

Reputation: 27611

Note that AuthorizationExecuteWithPrivileges has been deprecated for quite some time now.

As @RobNapier suggests in his comprehensive answer, you should be creating a helper app that is registered with launchd, which will provide the required elevation for the helper.

The EvenBetterAuthorizationSample is what you should be aiming for, but it's quite involved if you're coming to it for the first time, especially as it uses XPC communication between the application and its helper.

SMJobBless is a simpler example that can help you get started and understand the concepts for creating a separate helper application.

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299305

Use AuthorizationMakeExternalForm to create a serializable version of your authorization token. You can store this for a limited time for use between your applications. Deserialize it with AuthorizationCreateFromExternalForm. See Authorization Services Programming Guide for details. A key detail that is kind of buried is the constant kAuthorizationExternalFormLength. You'll need that to know how big an object you're serializing (it's 32 bytes, but use the constant).

This token is extremely sensitive, so you must be very careful with how you store it. It is generally better to create a separate privileged helper tool that your application can communicate with. See EvenBetterAuthorizationSample for sample code on how to do this in 10.8+ using XPC. (If you need pre-10.8, there used to be sample code called BetterAuthorizationSample that worked back to 10.6. Apple has taken it down, but you can find copies with google).

A privileged helper tool is more complicated to set up, but is much more secure. You use launchd to start it, then you pass it an authentication token (using AuthorizationMakeExternalForm). Launchd will automatically keep it running (and therefore authenticated) until it's been idle for a period of time. Then launchd will automatically kill it. This gets rid of all the security headaches of writing the auth token to a file.

Upvotes: 3

Related Questions