Slovvik
Slovvik

Reputation: 25

How to run bash with root rights in C program?

I have to write program in C that run bash with root rights. I try to do this with exec but i dont how to login. Is this a good idea?

int main() {
    char *name[2];
    name[0] = "bash";
    name[1] = NULL;
    execvp("/bin/bash", name);
}

Upvotes: 1

Views: 1785

Answers (1)

dbush
dbush

Reputation: 224387

Your executable needs to be setuid-root for this to work.

sudo chown root:root myprog 
sudo chmod 4755 myprog

Even if you do this, the shell might not give you root privileges if only the effective user ID is root. You'll need to set the real user ID as well:

int main() {
    char *name[2];
    name[0] = "bash";
    name[1] = NULL;
    setuid(0);      // sets the real user ID to 0 i.e. root
    execvp("/bin/bash", name);
}

Upvotes: 3

Related Questions