1

I need to create a file under the "/Library/Preferences/" Mac directory. But in Lion only root user have write privilege to this dir.

#include <stdio.h>

int main()
{
    FILE *fileHandle = NULL;
    fileHandle = fopen("/Library/Preferences/v.test", "w");
    fclose(fileHandle);

    return 0;
}

this line of code works if I run this code as sudo ./a.out. I wants to do the same programmatically.

Thanks!

phoxis
  • 60,131
  • 14
  • 81
  • 117
Vivek Kumar
  • 4,822
  • 8
  • 51
  • 85
  • 2
    if you could do that, anyone could break security, no? – Tom Zych Aug 24 '11 at 11:23
  • Why do you need to do this - why not set preferences for each user when they run it - so don't need admin rights – mmmmmm Aug 24 '11 at 11:32
  • It's possible if your program read the root password from input. But there's no difference between this way and `sudo ./a.out`. – Stan Aug 24 '11 at 11:32

5 Answers5

4

can you set the executable to setuid? Just chown it to root and chmod u+s.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • `root`. That is clear. But it is a "do once" action, none that would need to be done continuously. – glglgl Aug 24 '11 at 20:14
2

You can call setuid(0) from C to change your user id to root. The program will need to be owned by root and set as setuid allowed:

chown root:root a.out
chmod u+s a.out
JJ.
  • 5,425
  • 3
  • 26
  • 31
1

I don't think there is a way to achieve this (i.e. without manually granting some special rights to the program prior to execution) - and it is good that there isn't. Any such method would be a prime OS security vulnerability. If you could write such a program which takes root privileges, any malware maker could too...

Péter Török
  • 114,404
  • 31
  • 268
  • 329
0

Not an easy thing to do but still doable. Search for SMJobBless example from Apple. In general, it sets up launchd daemon which is run in launchd instance owned by root.

DimaA6_ABC
  • 578
  • 4
  • 15
0

Ask the user to login as root and launch the program when such a privileged work is to be done.

phoxis
  • 60,131
  • 14
  • 81
  • 117