Monday 9 January 2012

How to Run a C program/Shell script with root privilege

This method for creating a script that runs as root automatically.
  1. Open a text editor, and type up your script:
    #!/bin/sh
    program1
    program2
    ...
  2. Save the file as something.sh.
  3. Open a terminal, and enter the following commands:
    $ su
    [enter password]
    chown root:root something.sh
    chmod 4755 something.sh
    exit
    
  4. Then, finally run it with ./something.sh, and it'll have root access!
...or not. Most likely, you'll get the same error messages that you did before you ran those commands. If your script does actually work,
Take the down part for executing it.

The problem The instructions are fairly straightforward. Create the shell script that you want to execute, and change the owner and group to root (chown root:root). Now comes the command that's supposed to do the magic:
chmod 4755

Except it doesn't. Well, the truth is actually that the setuid bit is disabled on a lot of *nix implementations due the massive security holes it incurs. If the method originally mentioned doesn't work for you, chances are that your Linux distribution has disabled setuid for shell scripts.

The solution(s) One way of solving this problem is to call the shell script from a program that can use the setuid bit. For example, here is how you would accomplish this in a C program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
   setuid( 0 );
   system( "/path/to/script.sh" );

   return 0;
}

chown root:root runscript
chmod 4755 runscript

Now, you should be able to run it, and you'll see your script being executed with root permissions.
Conclusion With all that said, running shell scripts with setuid isn't very safe, and the distro designers had a pretty good idea of what they were doing when many of them disabled it. If you're running a multiuser Unix environment and security is an asset for you, make sure that your scripts are secure. A single slip can result in the compromising of an entire network. Only use them when absolutely necessary, and make sure you know exactly what you're doing if you do decide to use them.

No comments:

Post a Comment