2

I would like to execute one of my sudo commands through one of my C demon.

I use the command system(echo MYPASSWORD | sudo -v -S); in my C code.

It runs fine when I execute the demon. However, when I exit from the terminal it fails with a return value of 256.

Please suggest to me some alternate way to pass the password when the process is running in the backend.

Milan
  • 1,743
  • 2
  • 13
  • 36
Monoj Khatua
  • 33
  • 1
  • 1
  • 3
  • Maybe you should have a look at PolicyKit? http://www.freedesktop.org/wiki/Software/polkit/ – Jean-Michaël Celerier Aug 31 '13 at 11:51
  • 4
    Oh, and also, if you write your password like this in your code, there is a huge chance somebody can get it by running `strings YourProgram` in a shell. – Jean-Michaël Celerier Aug 31 '13 at 11:52
  • 6
    "If you need root privileges every time, the best thing is to start your program as root and drop them (in a subprocess) with setuid and setgid", [How to programmatically gain root privileges?](http://stackoverflow.com/questions/2483755/how-to-programmatically-gain-root-privileges) – cpp Aug 31 '13 at 12:04

2 Answers2

2

Some SUDO versions use open("/dev/tty") to ensure that the password cannot be sent this way. You could do the following to avoid this:

int ptm=open("/dev/ptmx"....);
int pid=fork();
if(!pid)
{
    close(0);
    close(1);
    close(2);
    setsid();
    unlockpt(...); grantpt(...);
    pts=open(ptsname...);
    execl(getenv("SHELL"),"sh","-c","sudo any_command",NULL);
    exit(1);
}
// now the ptm file handle is used to send data
// to the process and to receive output from the process
waitpid(...);

When all ttys are closed, setsid() is called and a new tty is opened (here the /dev/ptsn) then the new tty becomes the /dev/tty for the process. This means: sudo will read the password from the pseudo-terminal.

EDIT

I just fixed a bug in my example: open("/dev/ptmx" ...) should be called before fork().

Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38
0

Another option is to execute sudo commands without a password. To do that you can open the file /etc/sudoers with your favourite editor and add this line at the end. Remember to change the yourname with the user name.

yourname ALL = (ALL) NOPASSWD: ALL

Christos Papoulas
  • 2,469
  • 3
  • 27
  • 43
  • Actually sudo is not my main Problem, The main problem is getting input from stdin even if my terminal is closed. Just think about this code : ` system("echo PASSWORD | passwd USERNAME --stdin"); ` – Monoj Khatua Aug 31 '13 at 18:06
  • 1
    Maybe you need to have a shell script doing this job and take the password as parameter. So, the C program call the `system(sh script.sh PASSWORD)` and the script includes the code that is above. – Christos Papoulas Aug 31 '13 at 18:21