I need to move system files with NSFileManager in my application and I don't seem to have root access. What would be the easiest way to go about gaining this privilege?
I have looked into the BetterAuthorizationSample code provided by Apple, and I don't seem how I could have the NSFileManager run its task once its been given approval by the user.
Update: To update people still using this answer for reference, BLAuthentication
makes use of an old, and highly unrecommended function called AuthorizationExecuteWithPriviledges
that, while working, goes against the modern security paradigm, and is deprecated (and has been for a while). You're still allowed to use it, technically, but if you're developing for Mac OS X Lion, you're more than welcome to use the ServicesManagement framework, that allows you to run code with privileges as a helper tool.
For reference on how to create and launch a privileged helper tool, take a look at one of my questions, Writing a Privileged Helper Tool with SMJobBless().
There's no real easy way to authorize NSFileManager
, so you should look into using the standard mv
and cp
tools run under administrator authentication with the BLAuthentication
class. Unfortunately, the original author's website is down, but you can easily find copies of the class floating around on Google (I can also upload a copy for you if you wish).
With BLAuthentication
, what you are trying to do goes something like this:
#define MOVE @"/bin/mv"
if (![[BLAuthentication sharedInstance] isAuthenticated:MOVE]) {
[[BLAuthentication sharedInstance] authenticate:MOVE];
}
NSArray *arguments = [NSArray arrayWithObjects:@"location1", @"location2", nil];
[[BLAuthentication sharedInstance] executeCommand:MOVE withArgs:arguments];
The code above will prompt the user for the administrator's password and authenticate the program for the default time limit of five minutes.
WARNING
Of course, always be careful with system files! Avoid moving or manipulating them when possible, especially if your program is going to be run on someone else's computer (if anything goes wrong, you're going to be blamed)!
If you application needs to use root privileges, use Apple's Authorization Services API.
http://developer.apple.com/library/mac/#documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html#//apple_ref/doc/uid/TP30000995-CH204-TP1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With