5

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 -

Community
  • 1
  • 1
PhilBot
  • 748
  • 18
  • 85
  • 173

1 Answers1

3

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.

André Puel
  • 8,741
  • 9
  • 52
  • 83
  • 2
    You can also create an auxiliary executable which only a certain user (or group) can run with root permissions, which is just a bit less dangerous. – rici Feb 13 '13 at 20:04
  • 1
    This is technically correct. But I think the "it is dangerous" note is terribly underemphasized. Implementing this utility "perfectly" -- a perfectly secure setuid root binary that did nothing but purge the VM cache without side effect -- **is, straight up, a denial of service attack waiting to happen** for many (probably most) workloads out there. If you must have a setuid helper, this is how you do it. But don't do this. Find a better way to solve your problem. – Andy Ross Feb 13 '13 at 22:43
  • 3
    @AndyRoss I dont think there is a better way to solve the problem – André Puel Feb 13 '13 at 22:48