-3

I writing a program that is used by a parent process. I cannot control the parent process, its permissions, and how it runs my process.

My program runs a device that needs root permissions, while the parent process does not have the corresponding permissions.

Tried to use setuid(0); setgid(0); in my program. Also, tried to add the user of the process to use sudo. In addition, I run the solutions below. Does not works

The code

if(dry_run == 0)
{
    PRINT("reached here\n");
    ret =  ioctl((int64_t)device, NVME_IOCTL, &usr_io_cmd);
}

if (ret != 0 ) {
    PRINT("ERROR : error %x returned\n", ret);
    PRINT( "%s\n",strerror(errno) );

Where PRINT prints to a log file.

The log file

[2019-09-05 14:27:25] reached here

[2019-09-05 14:27:25] ERROR : error ffffffff returned

[2019-09-05 14:27:25] Operation not permitted

What can my program do? How can I implement "sudo su" in my program? Is there an alternative solution?

Edit: why this question is locked? I tried the solutions below and it did not worked.

user3563894
  • 331
  • 3
  • 13
  • why is the question downgraded? :( – user3563894 Sep 05 '19 at 11:54
  • 2
    Not my DV, but you haven't shown much effort that you made to solve the problem. Consider adding the code that you've tried for starters. – J...S Sep 05 '19 at 12:04
  • @user3563894 You haven't shown what you've tried and why it doesn't work. – S.S. Anne Sep 05 '19 at 12:09
  • Done. Described what I tried to do and failed. – user3563894 Sep 05 '19 at 12:15
  • Don't describe your code - post it. – Andrew Henle Sep 05 '19 at 12:15
  • Done. Now the code is published – user3563894 Sep 05 '19 at 12:31
  • Current **close reason** ("recommendation") is actually **bad**: It should be a "duplicate" for https://stackoverflow.com/questions/2483755/how-to-programmatically-gain-root-privileges or other similar question. And, according to answers to that question, the code isn't required for your question: gaining root privileges cannot be done *programmatically*, the only way is to set SUID or GUID bits for your executable. – Tsyvarev Sep 07 '19 at 07:15

1 Answers1

3

What you need to do is to have your program have the setuid or setgid bit set in the file permissions. This will cause the running process to have the effective user id of that of the program owner (setuid) or effective gid that of the program group (gid). You then can perform actions as those identities or become those with setuid and setgid.

sudo su is a cargo-cult way of doing things - both are programs that more or less do the same thing - elevate permissions of an unprivileged caller.

I.e. to have the program foo owned by root with setuid bit set, you'd do:

gcc foo.c -o foo
sudo chown root:root foo
sudo chmod 4755 foo