歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> UNIX文件權限之“設置用戶ID位”

UNIX文件權限之“設置用戶ID位”

日期:2017/2/28 13:59:46   编辑:Linux教程

用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 1.txt
-rw------- 1 root root 16 4月 29 14:31 1.txt

當前目錄下面有一個文件“1.txt”是所有者root,並且只有root具有讀和寫權限。

1 int main()
2 {
3 int fd;
4 if((fd=open("1.txt",O_RDONLY)) == -1)
5 {
6 printf("Open failed.\n");
7 exit(-1);
8 }
9 char buf[1024]={0};
10 read(fd,buf,1024);
11 printf(buf);
12 printf("\n");
13 }

  首先我在終端裡使用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程序,主要代碼如下:

1 struct stat buf = {0};
2 stat("main",&buf);
3 buf.st_mode |= S_ISUID;
4 chmod("main",buf.st_mode);

  執行後,main的“設置用戶ID位”就打開了。再在非root終端下 執行main程序 就可以成功的讀出 1.txt的內容 

$ main
linuxidc.com

個人覺得linux權限設計還是比較合理的,雖然這裡main程序可以運行時是已所有者root的權限,但是這需要root用戶的授權:打開這個程序文件的“set uid bit”(設置用戶ID位)。只要在打開這個set uid bit 時充分考慮到這個程序存在的風險。當然授權需謹慎。O(∩_∩)O

Copyright © Linux教程網 All Rights Reserved