Switches UID to a new user, and preserving CAP_NET_ADMIN capabilities

在linux中每个进程有三个[实际上有第4个]用户标识符.
real uid : 真实用户ID.
saved uid : 已保存用户ID
effective uid : 有效用户ID
真实用户ID(real uid)是login时的用户.而在运行过程中,
用于所有的安全检查的是有效用户ID(effective uid).
一般情况下:
real uid = saved uid = effective uid

在某些场合下,使用用setuid,setruid函数可以改变effective uid,从而
使得程序运行时具有特殊的权限. 

假如又想保留原来的一些资源权限,可以这么做

//保留原先的capabilities

prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
setuid(NEW_UID);

//增加新的capatilities

capset(&header, &cap);

其中NEW_UID是新UID,关于prctl,

prctl - operations on a process
       prctl() is called with a first argument describing what to do (with values
       defined in <linux/prctl.h>), and further arguments with a significance
       depending on the first one.  
来看看这个参数 PR_SET_KEEPCAPS
       PR_SET_KEEPCAPS (since Linux 2.2.18)
              Set the state of the thread's "keep capabilities" flag, which
              determines whether the threads's permitted capability set is cleared
              when a change is made to the threads's user IDs such that the threads's
              real UID, effective UID, and saved set-user-ID all become nonzero when
              at least one of them previously had the value 0.  By default, the
              permitted capability set is cleared when such a change is made; setting
              the "keep capabilities" flag prevents it from being cleared.  arg2 must
              be either 0 (permitted capabilities are cleared) or 1 (permitted
              capabilities are kept).  (A thread's effective capability set is always
              cleared when such a credential change is made, regardless of the
              setting of the "keep capabilities" flag.)  The "keep capabilities"
              value will be reset to 0 on subsequent calls to execve(2).
posted @ 2013-01-10 16:15  _yma  阅读(645)  评论(0编辑  收藏  举报