Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute commands as root without root password or sudo

Tags:

c

linux

root

setuid

I understand the implications of running a script as root, especially by a web application. However as part of my web application, I need to use curl with tor and this needs resetting the tor ip occasionally. tor can get a new ip when the service is restarted with service tor restart. Since only root can do that, I've written a C wrapper script to do what I need, and compiled it and set setuid root on it, and changed to root user ownership. However, it still asks me root password when it's run as an unprivileged user. As root, a service restart shouldn't ask password.

My script:

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

void ExecAsRoot (char* str);
int main ()
{
  setuid (0);
  setvbuf(stdout, NULL, _IONBF, 0);
  printf ("Host real ip is: ");
  ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
  ExecAsRoot("/usr/sbin/service tor restart");
  // sleep(2);
  printf ("Tor should have switched to a new ip by now.\nNew ip is: ");
  ExecAsRoot("torify curl ifconfig.co 2>/dev/null");
  return 0;
 }

void ExecAsRoot (char* str) {
  system (str);
}

I've done the following:

chown root restartor
chmod u=rwx,go=xr restartor 

Output:

Host real ip is: 7.17.11.23
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to restart 'tor.service'.
Authenticating as: root
Password:

How can I get this to run as web user without supplying root password?

like image 969
Joel G Mathew Avatar asked Aug 02 '17 19:08

Joel G Mathew


1 Answers

You didn't set the setuid bit in the file permissions:

#-------v
chmod u=srwx,go=xr restartor
like image 199
dbush Avatar answered Oct 05 '22 23:10

dbush