Skip to content

Instantly share code, notes, and snippets.

@autoxr
Created July 16, 2009 03:36
Show Gist options
  • Save autoxr/148146 to your computer and use it in GitHub Desktop.
Save autoxr/148146 to your computer and use it in GitHub Desktop.
- (BOOL)getRoot
{
OSStatus err = errAuthorizationSuccess;
if (!_authRef)
{
AuthorizationItem item[1];
AuthorizationFlags authFlags = kAuthorizationFlagDefaults;
AuthorizationRights authRights;
authRights.count = 0;
authRights.items = NULL;
err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, authFlags, &_authRef);
if (err == errAuthorizationSuccess)
{
item[0].name = kAuthorizationRightExecute;
item[0].value = NULL; // I think this is ignored, it should probably be a cString.
item[0].valueLength = 0;
item[0].flags = 0;
authRights.count = 1;
authRights.items = item;
authFlags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
err = AuthorizationCopyRights(_authRef,&authRights,kAuthorizationEmptyEnvironment,authFlags,NULL);
}
}
if (err != errAuthorizationSuccess)
{
if (_authRef)
{
AuthorizationFree(_authRef,kAuthorizationFlagDestroyRights);
_authRef = NULL;
}
}
return (err == errAuthorizationSuccess);
}
- (BOOL)elevateMyPrivs
{
BOOL success = NO;
if ([self getRoot])
{
NSString *grantrights = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"grantrights"];
int pid = [[NSProcessInfo processInfo] processIdentifier];
char pidstr[10];
sprintf(pidstr,"%d",pid);
char * const args[2] = {pidstr,0};
FILE *conn = NULL;
if (AuthorizationExecuteWithPrivileges(_authRef, [grantrights fileSystemRepresentation], 0, args, NULL) == errAuthorizationSuccess)
{
int pid, status;
pid = wait(&status);
if ((pid != -1) && WIFEXITED(status))
{
success = (WEXITSTATUS(status) == 0);
}
}
}
return success;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment