问题: 如下这个文件,由root账号创建,权限为
rw-r-----,即对普通用户来说,read/write权限都没有.
-rw-r----- 1 root root 0
7月 9 21:22 rootfile
在非root账号即普通用户账号下,试图读取该文件会报错:
$ cat rootfile
cat: rootfile: 权限不够
在某些特殊情况下,普通用户也需要读取该文件的内容.怎么办?
解决办法:
1. 编写一个owner id为root的程序,读写rootfile,名为 ReadRootFile(源代码见下文
)。此时该程序只能由root账号执行。
-rwxr-xr-x 1 root root 8968 7月 9
21:37 ReadRootFile
如果尝试在普通账号下运行该程序,会报错:
$ ./ReadRootFile rootfile
Open fail: : Permission denied
Real User ID:1000, name=liuwei
Effective User ID:1000, name=liuwei
2. 在root账号下,执行 chmod u+s ./ReadRootFile,打开 Set-User-ID
位。设置后,再次查看文件属性。可见文件的用户可执行权限位变成了s,表示修改成功。
$ sudo chmod u+s ./ReadRootFile
$ ls -l ReadRootFile
-rwsr-xr-x 1 root root 8968 7月 9 21:37 ReadRootFile
3. 切换到普通账号,再次运行 ./ReadRootFile,成功打开rootfile.
$ ./ReadRootFile ./rootfile
Open ./rootfile ok.
Real User ID:1000, name=liuwei
Effective User ID:0, name=root
注意第1步和第3步前后对比,Effective User ID和Name发生了变化.
原理解释:
首先说明几个概念.
Owner ID: 文件的拥有者,即我们通过 ls -l 看到的名字.ReadRootFile的Owner
ID为root.
Real User ID: 进程的实际用户ID,我们在哪个账户下运行该进程,那进程的Real User ID就是这个账户.
Effective User ID: 进程的有效用户ID. 默认情况下,Effective User ID等于Real
User ID.但通过chmod u+s设置了Set-User-ID后,Effective User ID就等于进程的Owner
ID.
如果进程的Effective User ID与文件的Owner
ID相同,则该进程有权限访问该文件。应用至Group同样成立。
本来rootfile只能允许root和root组账户才能访问,但执行上面第2步后,在普通账户liuwei下运行./ReadRootFile,此时进程的Effective
User ID变成了ReadRootFile的Owner ID,即root。因此,也可以成功访问rootfile。
ReadRootFile.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
char * get_username_by_id(uid_t uid)
{
struct passwd
*pwd;
pwd =
getpwuid(uid);
return (pwd == NULL) ?
NULL : pwd->pw_name;
}
int main(int argc, char *argv[])
{
int fd;
fd = open(argv[1], O_RDWR);
if(fd == -1)
perror("Open fail: ");
else
printf("Open %s ok.\n", argv[1]);
printf("Real User ID:%d, name=%s\n",
getuid(), get_username_by_id(getuid()));
printf("Effective User ID:%d, name=%s\n",
geteuid(), get_username_by_id(geteuid()));
close(fd);
return 0;
}
---------------------
作者:不是大牛的小刘
来源:CSDN
原文:https://blog.csdn.net/weixin_42263483/article/details/80977701
版权声明:本文为博主原创文章,转载请附上博文链接!