Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa - Gaining Root Access for NSFileManager

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.

like image 818
lab12 Avatar asked Jan 04 '11 23:01

lab12


2 Answers

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)!

like image 173
Itai Ferber Avatar answered Sep 22 '22 07:09

Itai Ferber


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

like image 41
Stephen Melvin Avatar answered Sep 21 '22 07:09

Stephen Melvin