用stat函数可以获取一个文件的状态信息,原型是这样的:

int stat(const char *path, struct stat *buf);

  其中结构体stat的结构:

struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};

    从传出的参数buf中可以拿到用st_uid,st_gid 表示的文件所有者ID,和文件所有者所在的组ID。

  在UNIX进程中也有几组ID的概念。分别是实际用户ID,实际用户组ID,有效用户ID和有效用户组ID等等。当我们开始一个进程是,通常这个进程的有效用户ID就是这个进程的实际ID(比如我用eric用户登录,这个有效用户就我eric对应的ID)。然而当“设置用户ID位”打开以后,有效ID就是进程的程序文件对应的所有者的ID。

  

$ls -l .txt
-rw------- root root 4月 : .txt

  当前目录下面有一个文件“1.txt”是所有者root,并且只有root具有读和写权限。

 int main()
{
int fd;
if((fd=open("1.txt",O_RDONLY)) == -)
{
printf("Open failed.\n");
exit(-);
}
char buf[]={};
read(fd,buf,);
printf(buf);
printf("\n");
}

  首先我在终端里使用su命令使用root用户。gcc read.c -omain。得到main程序。

# gcc read.c -omain
# exit
exit
$ main
Open failed.

  显然main的所有者也是root,但是main程序依旧不可以打开“1.txt”,这是因为main启动后这个进程的有效ID是进程的实际用户ID(也就是eric账户的ID),而“1.txt”只对root用户具有读写权限,所以open失败。

  把main的设置用户ID位打开可以用shell指令: chmod u+s main

  我用的是c程序,主要代码如下:

         struct stat buf = {};
stat("main",&buf);
buf.st_mode |= S_ISUID;
chmod("main",buf.st_mode);

  执行后,main的“设置用户ID位”就打开了。再在非root终端下 执行main程序 就可以成功的读出 1.txt的内容 

$ main
ilovecpp.com

  

个人觉得linux权限设计还是比较合理的,虽然这里main程序可以运行时是已所有者root的权限,但是这需要root用户的授权:打开这个程序文件的“set uid bit”(设置用户ID位)。只要在打开这个set uid bit 时充分考虑到这个程序存在的风险。当然授权需谨慎。O(∩_∩)O

04-16 07:37
查看更多