• Stars
    star
    386
  • Rank 107,550 (Top 3 %)
  • Language
    Objective-C
  • License
    BSD 3-Clause "New...
  • Created over 12 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An NSTask-like wrapper around the macOS Security Framework's AuthorizationExecuteWithPrivileges function to run shell commands with root privileges in Objective-C / Cocoa.

STPrivilegedTask - Objective-C class

An NSTask-like wrapper class around AuthorizationExecuteWithPrivileges() in the macOS Security API to run shell commands with root privileges.

STPrivilegedTask was created a long time ago. It has been updated over the years to work with the latest versions of macOS and is available via CocoaPods.

Examples

Create and launch task

// Create task
STPrivilegedTask *privilegedTask = [STPrivilegedTask new];
[privilegedTask setLaunchPath:@"/usr/bin/touch"];
[privilegedTask setArguments:@[@"/etc/my_test_file"]];

// Setting working directory is optional, defaults to /
// NSString *path = [[NSBundle mainBundle] resourcePath];
// [privilegedTask setCurrentDirectoryPath:path];

// Launch it, user is prompted for password (blocking)
OSStatus err = [privilegedTask launch];
if (err == errAuthorizationSuccess) {
    NSLog(@"Task successfully launched");
}
else if (err == errAuthorizationCanceled) {
    NSLog(@"User cancelled");
} 
else {
    NSLog(@"Something went wrong");
}

See Authorization.h for a list of possible error codes.

Launch task one-liner

OSStatus err = [STPrivilegedTask launchedPrivilegedTaskWithLaunchPath:@"/bin/sh" 
                                                            arguments:@[@"/path/to/script.sh"]];

Getting task output

// ... Launch task

[privilegedTask waitUntilExit]; // This is blocking

// Read output file handle for data
NSData *outputData = [[privilegedTask outputFileHandle] readDataToEndOfFile];
NSString *outputString = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];

Getting output while task runs in background

// ... Launch task

NSFileHandle *readHandle = [privilegedTask outputFileHandle];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(getOutputData:)
                                             name:NSFileHandleReadCompletionNotification
                                           object:readHandle];
[readHandle readInBackgroundAndNotify];

// ...

- (void)getOutputData:(NSNotification *)aNotification {
    // Get data from notification
    NSData *data = [[aNotification userInfo] objectForKey:NSFileHandleNotificationDataItem];
    
    // Make sure there's actual data
    if ([data length]) {
        // Do something with the data
        NSString *outputString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", outputString);

        // Go read more data in the background
        [[aNotification object] readInBackgroundAndNotify];
    } else {
        // Do something else
    }
}

Task termination

You can observe STPrivilegedTaskDidTerminateNotification:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(privilegedTaskFinished:)
                                             name:STPrivilegedTaskDidTerminateNotification
                                           object:nil];

- (void)privilegedTaskFinished:(NSNotification *)aNotification {
    // Do something
}

Or alternatively, set a termination handler:

privilegedTask.terminationHandler = ^(STPrivilegedTask *privilegedTask) {
    NSLog(@"Terminating task: %@", [privilegedTask description]);
};

Launch using external AuthorizationRef

// ... Create your own AuthorizationRef

[STPrivilegedTask launchedPrivilegedTaskWithLaunchPath:@"/bin/sh"
                                             arguments:@"/path/to/script"
                                      currentDirectory:@"/"
                                         authorization:authRef]

AuthorizationExecuteWithPrivileges() is deprecated

AuthorizationExecuteWithPrivileges() is deprecated as of macOS 10.7 but still remains available in macOS 12 "Monterey". If you want to be future-proof, here's how you check if STPrivilegedTask works in the running version of macOS:

OSStatus err = [privilegedTask launch];
if (err == errAuthorizationFnNoLongerExists) {
    NSLog(@"AuthorizationExecuteWithPrivileges not available");
}

If you need to check whether STPrivilegedTask works before you launch the task:

BOOL works = [STPrivilegedTask authorizationFunctionAvailable];

Sample app

A sample app which makes use of STPrivilegedTask is included in the project. This app runs the following script:

#!/bin/sh

echo "/usr/bin/whoami:"
whoami
echo ""
echo "Real User ID:"
echo $UID \($USER\)
echo ""
echo "Effective User ID:"
/usr/bin/id -u
echo ""
echo "Current working directory:"
echo "$PWD"

exit 5

It then presents the output of the script in a window, along with the exit code.

BSD License

Copyright (c) 2008-2021 Sveinbjorn Thordarson <[email protected]> All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

More Repositories

1

Sloth

Mac app that shows all open files, directories, sockets, pipes and devices in use by all running processes. Nice GUI for lsof.
Objective-C
7,949
star
2

Platypus

Create native Mac applications from command line scripts.
Objective-C
2,517
star
3

hear

Command line speech recognition and transcription for macOS
Objective-C
147
star
4

ManDrake

Native Mac man page editor with syntax coloring, mandoc syntax checking & live preview.
Objective-C
142
star
5

DataURLToolkit

Various tools for working with Data URLs, incl. web application (http://dataurl.net), Mac OS X GUI app, command line tool, Perl modules and Apache module.
Perl
107
star
6

osxiconutils

A suite of command line utilities for working with Mac icons
Objective-C
104
star
7

searchfs

Command line tool to quickly search by filename on entire APFS and HFS+ volumes using the file system catalog.
Objective-C
98
star
8

KatSearch

Fast, simple, powerful filesystem search for macOS, just like the good ol' days.
Objective-C
97
star
9

FastDMG

Fast, no-nonsense disk image mounting for macOS
Objective-C
89
star
10

Phew

FLIF image viewer and QuickLook plugin for macOS
Objective-C
82
star
11

lemur2013

WordPress theme for lemurinn.is
PHP
47
star
12

Dim

User-friendly, high quality document icon maker for OS X
Objective-C
42
star
13

SnapTools

Tools to integrate the macOS window environment and command line interface
Objective-C
40
star
14

IconScanner

Find and inspect macOS icon assets (.icns) on your system
Objective-C
30
star
15

ensk.is

A free and open English-Icelandic dictionary. https://ensk.is
Python
27
star
16

PixlView

Mac tool to view raw pixel data in a variety of formats
Objective-C
24
star
17

iceaddr

Python package to look up information about Icelandic street addresses, postcodes and placenames
Python
23
star
18

STPathTextField

Subclass of NSTextField that supports shell and browser-style path autocompletion
Objective-C
20
star
19

sagadb.org

Icelandic Saga Database
HTML
20
star
20

ochre

macOS optical character recognition via the command line
Objective-C
9
star
21

SnowboyFramework

Snowboy hotword detection engine packaged as an iOS framework
C++
8
star
22

docerator

GUI for the docerator.py program
Objective-C
7
star
23

ManOpen-Intel

Intel-buildable package of Carl Lindberg's ManOpen
C
7
star
24

BrowserPick

Control which macOS browsers should open which URLs using rules and hotkeys
Objective-C
7
star
25

cityloc

Python package to look up world city coordinates and country codes
Python
5
star
26

Pizarro

Quirky music-oriented iOS game implemented using Cocos2D and the Chipmunk physics engine
Objective-C
3
star
27

vafuglinn

Váfuglinn website
HTML
2
star
28

MalidMacService

Mac Service to look up Icelandic words on málið.is
Objective-C
2
star