Obtaining admin privileges to delete files using rm from a Cocoa app
Asked Answered
T

2

11

I am making a small app that deletes log files. I am using an NSTask instance which runs rm and srm (secure rm) to delete files.

I want to be able to delete files in:

  • /Library/Logs
  • ~/Library/Logs

The issue is that the user account does not have permissions to access some files in the system library folder, such as the Adobe logs subfolder and others. For example, only the "system" user (group?) has r/w permissions for the Adobe logs folder and its contents, and the current user doesn't even have an entry in the permissions shown in the Get Info window for the folder.

What I want to be able to do exactly:

  1. Obtain admin privileges.
  2. Store the password in the Keychain so the app doesn't have to nag the user each time (Is the storage of the password a bad idea? Is it possible?)
  3. Delete a file whatever the file permissions may be.

I am using NSTask because it offers notifications for task completion, getting text output from the task itself, etc. Would I need to use something else? If so, how could I replicate NSTask's completion notifications and output file handle while running rm and srm with admin privileges?

I am looking for the most secure way to handle the situation. i.e. I don't want my application to become a doorway for privilege escalation attacks.

I looked at the Authorization Services Programming Guide but I am not sure which case fits. At first I thought that AuthorizationExecuteWithPrivileges would be a good idea but after reading more on the subject it looks like this method is not recommended for security reasons.

A detailed answer would be very welcome. I'm sure some of you already had to do something similar and have some code and knowledge to share.

Thanks in advance!

Update:

I am now able to make the authentication dialog pop up and obtain privileges, like so:

OSStatus status;
AuthorizationRef authRef;
    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authRef);

AuthorizationRights authRights;
AuthorizationItem authItems[1];

authItems[0].name = kAuthorizationRightExecute;

authRights.count = sizeof(authItems) / sizeof(authItems[0]);
authRights.items = authItems;

AuthorizationFlags authFlags = kAuthorizationFlagDefaults | kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed;

status = AuthorizationCopyRights(authRef, &authRights, kAuthorizationEmptyEnvironment, authFlags, NULL);

From the looks of it, it seems that the "Factored Application" method looks the most appropriate. The thing is that, to me, rm already seems like an external helper tool. I'm not sure I get the setuid alternative suggested in the documentation. Could I set the setuid bit on rm and run it using the NSTask method I already implemented? This would mean that I wouldn't need to create my own helper tool. Could somebody elaborate on this subject?

I also looked at the BetterAuthorizationSample which is suggested as a more secure and recent alternative to the setuid bit method, but found it awfully complex for such as simple behavior. Any hints?

Thanks in advance for any help!

Tai answered 27/8, 2010 at 23:34 Comment(1)
I'm also very interested in this question. How delete file ~/Library/Logs & ~/Library/Caches. Have you a correct answer or solution?Auburta
C
4

I had this headache a few months ago. I was trying to get a shell script running with admin privileges that shutdown my computer at a certain time. I feel your pain.

I used the BetterAuthorizationSample which was a total nightmare to wade through. But I took the most pragmatic route - I didn't bother trying to understand everything that was going on, I just grabbed the guts of the code.

It didn't take me that long to get it doing what I wanted. I can't remember exactly what I altered, but you're welcome to check out my code:

http://github.com/johngallagher/TurnItOff

I hope this helps on your quest for a secure application!

Crystalcrystalline answered 31/8, 2010 at 17:46 Comment(5)
Thanks! I scanned through the code quickly but I am not sure what does what. In the products there is an helper app, plus an helper tool, an install tool, etc… do you have any details on what does what so I can better understand what I would need to include? Thanks for your time.Tai
After looking more into it, it seems that using the BetterAuthorizationSample code directly seems like the best option. Looking in the /Library/PrivilegedHelperTools folder, you can see that the BAS code was used in CCC and other know apps so I guess it's a reasonable solution. I am suprised that Apple didn't come up with a simpler way to authenticate and run privileged operations. Anyway I should be able to get this to work but any other hints would be nice. Thanks again.Tai
There are 4 products in my Xcode project. There's a Shutdown.prefPane, which is the UI. ShutdownHelperApp.app is my process that shuts down the machine at certain times of the day. HelperTool and InstallTool are from BetterAuthorizationSample. The main bit I remember changing is in SampleTool.c near the top - you'll see *shutdownCommand = "/opt/local/sbin/shutdown.sh"; - that's mine. I've also got the complete BetterAuthorizationSample code in a top level folder in the repo. You could do a diff on their files versus mine to find out what I changed since I can't remember what I changed.Crystalcrystalline
Thanks for the details. There is still something that bothers me though. If I understand well, BAS installs a privileged helper tool that does not need authentication to perform privileged operations once installed. If the operation I want to be able to do is delete files, and if the input of the helper tool can come from unprivileged applications, isn't the BAS method inherently insecure? I mean anyone could ask the helper tool to delete file X and it would do it. Or is there some kind of protection that prevents other apps from using the tool? There must be something I didn't get.Tai
I'm afraid that's something I can't help you out with. I just trusted that if that was the recommended way, Apple must have thought of this. I'm assuming that not just anyone could ask your helper tool to do anything via permissions, maybe? I don't know.Crystalcrystalline
W
9

Perhaps a tad late, but this might be useful for future reference for other people. Most of the code is from this person.

Basically, it has a lot to do with Authorization on the Mac. You can read more about that here and here.

The code, which uses the rm tool:

+ (BOOL)removeFileWithElevatedPrivilegesFromLocation:(NSString *)location
{
    // Create authorization reference
    OSStatus status;
    AuthorizationRef authorizationRef;

    // AuthorizationCreate and pass NULL as the initial
    // AuthorizationRights set so that the AuthorizationRef gets created
    // successfully, and then later call AuthorizationCopyRights to
    // determine or extend the allowable rights.
    // http://developer.apple.com/qa/qa2001/qa1172.html
    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
    if (status != errAuthorizationSuccess)
    {
        NSLog(@"Error Creating Initial Authorization: %d", status);
        return NO;
    }

    // kAuthorizationRightExecute == "system.privilege.admin"
    AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
    AuthorizationRights rights = {1, &right};
    AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed |
                                kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;

    // Call AuthorizationCopyRights to determine or extend the allowable rights.
    status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
    if (status != errAuthorizationSuccess)
    {
        NSLog(@"Copy Rights Unsuccessful: %d", status);
        return NO;
    }

    // use rm tool with -rf
    char *tool = "/bin/rm";
    char *args[] = {"-rf", (char *)[location UTF8String], NULL};
    FILE *pipe = NULL;

    status = AuthorizationExecuteWithPrivileges(authorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe);
    if (status != errAuthorizationSuccess)
    {
        NSLog(@"Error: %d", status);
        return NO;
    }

    // The only way to guarantee that a credential acquired when you
    // request a right is not shared with other authorization instances is
    // to destroy the credential.  To do so, call the AuthorizationFree
    // function with the flag kAuthorizationFlagDestroyRights.
    // http://developer.apple.com/documentation/Security/Conceptual/authorization_concepts/02authconcepts/chapter_2_section_7.html
    status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
    return YES;
}
Whack answered 7/6, 2011 at 18:29 Comment(3)
This method uses AuthorizationExecuteWithPrivileges that is deprecated in 10.7Necropsy
Use a helper application as AuthorizationExecuteWithPrivileges is deprecated: #6842437Aberration
suppose if you need to delete 500 files then it will as for password 500 times. Any resolution??Shang
C
4

I had this headache a few months ago. I was trying to get a shell script running with admin privileges that shutdown my computer at a certain time. I feel your pain.

I used the BetterAuthorizationSample which was a total nightmare to wade through. But I took the most pragmatic route - I didn't bother trying to understand everything that was going on, I just grabbed the guts of the code.

It didn't take me that long to get it doing what I wanted. I can't remember exactly what I altered, but you're welcome to check out my code:

http://github.com/johngallagher/TurnItOff

I hope this helps on your quest for a secure application!

Crystalcrystalline answered 31/8, 2010 at 17:46 Comment(5)
Thanks! I scanned through the code quickly but I am not sure what does what. In the products there is an helper app, plus an helper tool, an install tool, etc… do you have any details on what does what so I can better understand what I would need to include? Thanks for your time.Tai
After looking more into it, it seems that using the BetterAuthorizationSample code directly seems like the best option. Looking in the /Library/PrivilegedHelperTools folder, you can see that the BAS code was used in CCC and other know apps so I guess it's a reasonable solution. I am suprised that Apple didn't come up with a simpler way to authenticate and run privileged operations. Anyway I should be able to get this to work but any other hints would be nice. Thanks again.Tai
There are 4 products in my Xcode project. There's a Shutdown.prefPane, which is the UI. ShutdownHelperApp.app is my process that shuts down the machine at certain times of the day. HelperTool and InstallTool are from BetterAuthorizationSample. The main bit I remember changing is in SampleTool.c near the top - you'll see *shutdownCommand = "/opt/local/sbin/shutdown.sh"; - that's mine. I've also got the complete BetterAuthorizationSample code in a top level folder in the repo. You could do a diff on their files versus mine to find out what I changed since I can't remember what I changed.Crystalcrystalline
Thanks for the details. There is still something that bothers me though. If I understand well, BAS installs a privileged helper tool that does not need authentication to perform privileged operations once installed. If the operation I want to be able to do is delete files, and if the input of the helper tool can come from unprivileged applications, isn't the BAS method inherently insecure? I mean anyone could ask the helper tool to delete file X and it would do it. Or is there some kind of protection that prevents other apps from using the tool? There must be something I didn't get.Tai
I'm afraid that's something I can't help you out with. I just trusted that if that was the recommended way, Apple must have thought of this. I'm assuming that not just anyone could ask your helper tool to do anything via permissions, maybe? I don't know.Crystalcrystalline

© 2022 - 2024 — McMap. All rights reserved.