文件所有者ID是文件的性质,有效用户ID是进程的性质
1. 进程的有效用户ID是超级用户(值为0),则允许访问
2. 进程的有效用户ID等于文件所有者ID(该进程拥有此文件),那么若适当的访问权限位被设置,则允许访问。
3. 进程的有效组ID或进程的附加组ID 等于文件组ID,那么若适当的访问权限位被设置,则允许访问。
4. 进程的有效用户/组 ID 不属于前两种情况,那么若其他用户适当的访问权限位被设置,则允许访问。
当执行一个程序文件时,通常进程的 有效用户ID == 实际用户ID ,组ID == 实际组ID
设置用户/组ID位被设置时:当执行此文件时,将进程的有效用户ID设置为文件所有者的用户ID
举例:
hello 程序 —— 用于读取 hello.txt文件,并打印
hello.txt文本 —— 只包含 ”hello,world!"
文件属性如下:
-rwxr-xr-x 1 root root 5159 Dec 19 19:58 hello
-rwx------ 1 root root 13 Dec 19 17:02 hello.txt
如果在 ROOT用户下执行 hello 将正常返回:
[root@localhost test]# ./hello
Read char number:12,content:hello,world!
但是在非ROOT用户下执行,将无法读取 hello.txt的内容,因为执行 hello 的进程的有效用户ID为非ROOT,无法对 hello.txt进行读操作
[huenyifei@localhost test]$ ./hello
Read char number:-1,content:
如果修改 设置用户ID位:
[root@localhost test]# chmod u+s hello
-rwsr-xr-x 1 root root 5159 Dec 19 19:58 hello
-rwx------ 1 root root 13 Dec 19 17:02 hello.txt
此时在非ROOT用户下将正常执行,因为此时 hello进程的有效用户ID等于文件所有者ID 也就是 ROOT,该进程拥有 hello.txt文件,因此可以访问
[huenyifei@localhost test]$ ./hello
Read char number:12,content:hello,world!
接着我们来看一下,如果将 hello的文件所有者改为 非root 然后设置 设置用户ID位,看看会发生什么
[root@localhost test]# chown huenyifei:huenyifei hello;chmod u+s hello
-rwsr-xr-x 1 huenyifei huenyifei 5159 Dec 19 19:58 hello
[huenyifei@localhost test]$ ./hello
Read char number:-1,content:
可以看见程序无法读取 hello.txt的内容,这是因为hello的文件所有者改为 huenyifei 并设置 设置用户ID位,当非ROOT用户执行程序,进程的有效用户ID位被设置为文件所有者的ID,
即 huenyifei这个用户。所以自然无法对ROOT 所有的文件 hello.txt进行读操作。
其实这样也就是降低程序执行时权限的方法。
源码:
hello
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <fcntl.h>
-
#include <memory.h>
-
int main()
-
{
-
char buf[13];
-
memset(buf,0,sizeof(buf));
-
int n = 0;
-
int fd = open("/home/huenyifei/workspace/test/hello.txt",O_RDONLY);
-
n = read(fd,buf,sizeof(buf)-1);
-
printf("Read char number:%d,content:%s\n",n,buf);
-
return 0;
-
}
hello.txt
阅读(295) | 评论(0) | 转发(0) |