views:

341

answers:

2

What is the proper way to run something like $sudo touch folder_name or $sudo rm from within Objective-C/Cocoa? I'm changing and moving around a few files and need elevated privileges. Any code sample would be greatly appreciated. Thanks.

+5  A: 

One way to do it is AuthorizationExecuteWithPrivileges(), but that's discouraged for the normal course of things. Mainly it's for installers, I gather.

Something like:

AuthorizationRef auth = NULL;
OSStatus err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagInteractionAllowed, &auth);
err = AuthorizationExecuteWithPrivileges(auth, command, kAuthorizationFlagDefaults, args, NULL);

And you add appropriate checking of err...

See the Authorization documentation.

jeffamaphone
thanks this is exactly what I was looking for.
Jeff
+1  A: 

There are several ways to do this. Which one you choose depends on what you want to do. The simplest and unsafest way is to simple set the s-bit on an extra helper tool that you call from your code and does what needs admin rights. Take a look at the BetterAuthorizationSample for the most fancy and complicated way of executing privileged code.

The Authorization Services Programming Guide gives you all you need.

Hutaffe
“The simplest and unsafest way is to simple set the s-bit on an extra helper tool that you call from your code and does what needs admin rights.” That's actually the way Apple recommends. You're supposed to use `AuthorizationExecuteWithPrivileges` only to confer the setuid bit on the helper tool. The idea is to confine root powers to only the code that needs powers (the task-specific helper tool), so that code that doesn't need powers (your app) doesn't have them. It's the Principle of Least Privilege.
Peter Hosey