0

Suppose I want my C program, running on Linux, to execute a certain function which needs to run as the root user (e.g. it reads a root-owned file with permissions -rwx------). For simplicity, let's assume the function's signature int read_magic_file(int x).

If I wanted to do this outside my program, I would need to provide a password and use sudo (or su -c etc.) - but I want to do this within my program.

So, suppose I have determined a value for x, and that I've prompted my user for the root password and have gotten that password in a string. Now what do I do?

Notes:

  • My executable does not and will not have setuid permissions.
  • sudo will not be configured for my program to raise its own privileges, or to be run as root; nor will pam or anything else be configured to allow me to become root without a password etc.
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    This has _got_ to be a dupe of some other question... but I couldn't find one :-( – einpoklum Nov 28 '21 at 22:54
  • Does this help: https://stackoverflow.com/questions/34723861/calling-a-c-function-with-root-privileges-without-executing-the-whole-program – Jerry Jeremiah Nov 28 '21 at 23:00
  • 2
    Software can run as root without a password. Using `sudo` configuration, the `setuid` bit, or a more modern alternative: capabilities (`setcap`/`getcap`). – Cheatah Nov 28 '21 at 23:04
  • "does not have setuid permissions" If this means "must not and will not have setuid permissions", then `sudo` is the right solution. There are already *many* programs that rely upon that abstraction. – Jeff Holt Nov 28 '21 at 23:08
  • @JerryJeremiah: Well, it's a dupe of that question, yes; but the answers aren't all that helpful. – einpoklum Nov 28 '21 at 23:30
  • You cannot elevate the privilege of your process, but if you only want to read a file with root-privileges, you can call `sudo cat filename.txt` and capture its output. Oh, and don't use `system` or `popen` for this. They let the shell parse the command line, and if you don't get the quoting right (which nobody does), you end up with nasty security holes. Use proper `fork`/`exec`. – HAL9000 Nov 28 '21 at 23:53
  • @HAL9000: So, I can't use the capabilities mechanism for this? It doesn't let you gain privileges? – einpoklum Nov 29 '21 at 07:33
  • @einpoklum, the whole purpose of capabilities, is that a process cannot raise its own privileges while it is running. The only way a process can get more capabilities, is to have another privileged process create a file descriptor on its behalf. – HAL9000 Nov 29 '21 at 18:27
  • On Linux you can usually only reduce privileges, and after a certain point you can't go back. If you start unprivileged, you will have to delegate the job to some other privileged program. – Marco Bonelli Dec 01 '21 at 20:44

0 Answers0