Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically drop Linux cache as non-root user

For testing purposes, I can drop cached memory by writing to the drop_caches file in Linux under the procfs. I can only do this as root. This is on embedded Linux so there is no sudo.

sync; echo 3 > /proc/sys/vm/drop_caches

I can write to the file programmatically in c++ by doing something from the post --> How to programmatically clear the filesystem memory cache in C++ on a Linux system?

sync();
std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;

The challenge is wanting to do this while running the app as a non-root user. On reboot, the permissions look like:

# cd /proc/sys/vm/
# ls -lrt drop_caches 
-rw-r--r--    1 root     root             0 Feb 13 19:50 drop_caches

And you cannot seem to change those permissions - even as root:

# chmod 777 drop_caches 
chmod: drop_caches: Operation not permitted
# chown user:user drop_caches 
chown: drop_caches: Operation not permitted

How can I accomplish this on Linux? Is it possible to change permissions of a procfs file? I can fully customize my kernel if necessary. Thanks -

like image 494
PhilBot Avatar asked Oct 22 '22 17:10

PhilBot


1 Answers

You can create an auxiliary executable (be very careful, it is dangerous) which any user can run it with root permissions.

This is called setuid.

For safety reasons, you cannot setuid a shell script.

Extracting from the wiki how to use it:

The setuid and setgid bits are normally set with the command chmod by setting the high-order octal digit to 4 (for setuid) or 2 (for setgid). "chmod 6711 file" will set both the setuid and setgid bits (2+4=6)

Update

As @rici noted, you still will need to have execution permission to execute this process, so you can remove execution permission from others and keep it only on group. So, only who is member of the group can execute it.

like image 114
André Puel Avatar answered Oct 27 '22 22:10

André Puel