开发者

How to set CAP_SYS_NICE capability to a Linux user?

开发者 https://www.devze.com 2023-04-10 00:08 出处:网络
My program is using the Linux system call setprior开发者_JAVA技巧ity() to change the priorities of the threads it creates. It needs to set negative priorities (-10) but, as mentioned on the documentat

My program is using the Linux system call setprior开发者_JAVA技巧ity() to change the priorities of the threads it creates. It needs to set negative priorities (-10) but, as mentioned on the documentation, this fails when run as a normal user.

The user needs the CAP_SYS_NICE capability to be able to set the priorities as he wants, but I have no idea how to give such capability to the user.

So my question: how to set CAP_SYS_NICE capability to a Linux user?


There is a nice handy utility for setting capabilities on a binary: setcap. This needs to be run as root on your application binary, but once set, can be run as a normal user. Example:

$ sudo setcap 'cap_sys_nice=eip' <application>

You can confirm what capabilities are on an application using getcap:

$ getcap <application>
<application> = cap_sys_nice+eip

I'd suggest integrating the capabilities into your makefile in the install line, which is typically run as root anyhow. Note that capabilities cannot be stored in a TAR file or any derivative package formats. If you do package your application later on, you will need a script (postinst for Debian packages) to apply the capability on deploy.


Jan Hudec is right that a process can't just give itself a capability, and a setuid wrapper is the obvious way get the capability. Also, keep in mind that you'll need to prctl(PR_SET_KEEPCAPS, ...) when you drop root. (See the prctl man page for details.) Otherwise, you'll drop the capability when you transition to your non-root real user id.

If you really just want to launch user sessions with a different allowed nice level, you might see the pam_limits and limits.conf man pages, as the pam_limits module allows you to change the hard nice limit. It could be a line like:

yourspecialusername hard nice -10


AFAIK It's not possible to get a capability. Root processes have all capabilities and can give them up, but once given up, they can't be regained. So you'll need a suid-root wrapper that will give up all other capabilities and run the process.


Regarding sudo, I added the user like this:

niceuser ALL=NOPASSWD:/usr/bin/nice

And then it worked fine:

niceuser@localhost $ nice
0
niceuser@localhost $ sudo nice -n -10 nice
-10
0

精彩评论

暂无评论...
验证码 换一张
取 消