capabilities将系统root权限按功能单元划分,使用者按需打开/关闭相关权限,比基于UID的权限控制方式更精细。
不过,Linux下的capabilities是线程相关的,同一个进程的不同线程可以具有不同的capabilities权限,使用不当,可能会造成权限泄露。
可以使用libpsx规避该问题,它的原理很简单,就是把当前进程中所有线程的capabilities设置一遍。
下面以一个文件访问的例子进行说明。
相关背景知识:
本文的实验场景如下:
操作步骤:
sudo adduser master
sudo adduser slave
echo "Only current user can open me" > ~/test.txt
chmod 600 ~/test.txt
ls -l ~/test.txt
-rw------- 1 huo huo 26 1月 30 16:44 /home/huo/test.txt
gcc cap.c -lcap -lpthread
注:依赖libcap,ubuntu
可通过命令sudo apt install libcap-dev
命令安装。
sudo ./a.out
程序运行后,可以观察到以下结果:
main:235 pid:6755 tid:6755 Fail to open file. error:Permission denied
test_in_child_thread:182 pid:6755 tid:6756 Success to open file.
test_in_child_thread:182 pid:6755 tid:6757 Fail to open file. error:Permission denied