Linux下如何让普通用户运行特权程序访问受限文件

当普通用户需要读取root权限文件时,可以通过创建一个owner为root的程序并开启Set-User-ID位来实现。在root账号下,将程序的u+s权限设置好后,普通用户运行此程序,其Effective User ID会变为root,从而能访问受限文件。

问题: 如下这个文件,由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:

/*
 * getuid() returns the real user ID of the calling process.
 * geteuid() returns the effective user ID of the calling process.
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>

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()));
	/* 如果设置了Set-User-ID(chmod u+s),那Effective User ID与Owner ID相同。 */
	printf("Effective User ID:%d, name=%s\n",
		geteuid(), get_username_by_id(geteuid()));

	close(fd);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值