cit
cit

Reputation: 2605

Run a Bash script as root with Objective-C / Cocoa

Given that there is a file called copystuff in the Resources folder in a an xCode project, and that file reads:

#!/bin/sh
cp -R /Users/someuser/Documents /Users/admin/Desktop

And if this bit of code below is linked to a button in IB ... it will copy the /Users/someuser/Documents directory to /Users/admin when the button is pressed in a Cocoa app... It works when app is launched in an admin account ( using OS X 10.5.x here) ...

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle]
pathForResource:@"copystuff" ofType:@"sh"], nil]];
[task launch];

My question is.. is there a way to have NSTask run a script running as root while this code is called from a non-admin account? Or asked another way..can Objective-C be coded to run scripts from say /usr/bin as root from a non-admin account?

Upvotes: 3

Views: 5806

Answers (2)

Carl Norum
Carl Norum

Reputation: 224864

If I'm understanding what you want to do, you're trying to have a non-privileged user be able to perform a privileged action without needing to authenticate?

setuid shell scripts are considered a gigantic security risk, so they're disallowed by the kernel. If you want to write a separate executable program, however, you can set the set-user-ID-on-execution or set-group-ID-on-execution bits on it and get the behaviour you want. Be careful, you're now in the land of big potential security problems...

man chmod for more information.

Here's a quick and dirty example:

$ echo "Hello, world!" > file
$ sudo chown root file
$ sudo chmod 600 file
$ cat file
cat: file: Permission denied

But I can write a program:

#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  setuid(0);
  system("cat file");
  return 0;
}

Which can do what we'd like:

$ cc -Wall -o app main.c
$ chown root app
$ chmod 4755 app
$ ./app
Hello, world!

Upvotes: 4

Rob Napier
Rob Napier

Reputation: 299285

I would strongly recommend against using an external script like this. It's much better to do this with NSFileManager and keep this inside of controlled code. But to the question of how to become root, you want to look at Authorization Services. This site will walk you through how to create an application that escalates its privileges, including the appropriate UI elements for it.

Upvotes: 7

Related Questions