Friday, April 8, 2022

[SOLVED] Running C program as root without password

Issue

I want to write program in C which will open bash as root, but without password for any user.

#include <unistd.h>
#include <stdio.h>

int main(void)
{
    char *argv[] = { "/bin/bash","-c","sudo /bin/bash",0 };
    execve(argv[0], &argv[0],0);
    return 0;
}

My system is Linux Mint 18.2 Sonya, and i set these 2 commands

chown root:root a.out
chmod u=srwx,go=xr a.out

But still when i try to execute this, it asks for password. I don`t want to edit /etc/sudoers if there is any other option.


Solution

This is a HUGE security hole you're creating. Just so long as you're aware of it. In fact, I cannot understand why you don't want to edit sudoers, but are okay with a having a program where merely running it creates a root shell.

With that said, here is the program:

#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[], char *envp[]) {
  char *args[] = { "/bin/bash", NULL };
  execve(args[0], args, envp);

  perror("Running bash failed");
  return 1;
}

Now all you have to do is compile it, set the executable's file owner to root and set the SUID permission.

The reason your code failed is because SUID sets the effective UID. The real UID is still you, and so sudo asks for a password.

With that said, there is no reason to just run the shell as effective root, which is what the code above does.

One downside of this code is that it does not set the real UID to root, and does not perform a log in. If that's an issue for you, keep your original program, but add at its beginning:

setresuid(0, 0, 0);
setresgid(0, 0, 0);


Answered By - Shachar Shemesh
Answer Checked By - Robin (WPSolving Admin)