Open the file with administrator rights, but before you read it, release privileges?

TL DR

I am writing a C program. I need root privileges for fopenthe sysfs file, and I still need root privileges to read them. However, since my program will need to continuously read the sysfs file, this means that all this time I will need to have elevated privileges. I would like to reset root privileges as soon as possible. What is an acceptable way to solve this problem?

More details

I am writing a program that interacts with sysfs. If I were to run commands on the shell, I would use:

myuser@mymachine:~$ sudo su
root@mymachine:/home/myhomedir# cd /sys/class/gpio
root@mymachine:/sys/class/gpio# echo 971 > export
root@mymachine:/sys/class/gpio# cat gpio971/value
0
root@mymachine:/sys/class/gpio# exit

I need to run these commands in a C program that can be invoked by a non-privileged user. One way to do this - to record a program in the usual way by using fopen, fprintf, fscanfetc. And run the program through sudo. However, this means that the user must be sudoer, and the program will have root privileges all the time.

Another solution that I prefer (since the user does not need to add to sudoers), it is necessary to change the owner of the program to root and set the bit setuid. (I learned this from here ).

, - . sysfs, euid 0, ( ). , , setuid() UID . , , . :

//At this point, due to the file permissions on the executable,
//euid = 0 and ruid = 1000. I know the following 4 lines work.
FILE *export = fopen("/sys/class/gpio/export", "wb");
fprintf(export, "971\n");
fclose(export);

FILE *sw_gpio = fopen("/sys/class/gpio971/value", "rb");

setuid(1000);
//Now euid = 1000 and ruid = 1000

int switch_val = -1;
fscanf(sw_gpio, "%d", &switch_val);
printf("Switch value: %d\n", switch_val); //-1
//Even though the only possible values in this sysfs file are 0 and 1,
//switch_val is still equal to -1

fclose(sw_gpio);

, , /sys/class/gpio/gpio971/value. , ! , root .

, , , :

-rwsr-xr-x 1 root myuser 10943 Jan 1 20:17 main*

, root, sysfs ?

+4
1

/sysfs, , setuid(). , . , (Fedora 20 x64), open()/read() fopen()/fscanf().

0

Source: https://habr.com/ru/post/1684747/


All Articles