編譯運行:
案例二:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- void test_read_file(const char
*name)
- {
- int fd =
-1;
- fd = open(name
,O_RDWR);
- if(fd
< 0){
- printf("=[ERROR]:read failed.\n");
- }else{
- printf("=[OK]:read successful\n");
- close(fd);
- }
- }
- //打印uid和euid
- void p_states()
- {
- int uid = 0;
- int euid = 0;
- printf("------Current states--------\n");
- printf("real uid\t %d\n",getuid());
- printf("effective uid\t %d\n",geteuid());
- printf("----------------------------\n");
- }
- //調用setuid
- void run_setuid_fun(int uid)
- {
- if(setuid(uid)
==
-1)
- {
- printf("=[ERROR]:setuid(%d) error\n",uid);
- }
- p_states();
- }
- //調用setuid
- void run_seteuid_fun(int uid)
- {
- if(setuid(uid)
==
-1)
- {
- printf("=[ERROR]:seteuid(%d) error\n",uid);
- }
- p_states();
- }
- int main()
- {
- int t_re = 0;
- const char *file
= "root_only.txt";
- printf("\nTEST 1:\n");
- p_states();
- //此時real uid
= login user id
- //effective uid
= root
- //saved uid
= root
- test_read_file(file);
- getchar();
- printf("\nTEST 2:setuid(getuid())\n");
- run_seteuid_fun(getuid());
- //此時real uid
= login user id
- //effective uid
= login user id
- //saved uid
= root
- test_read_file(file);
- getchar();
- printf("\nTEST 3:setuid(0)\n");
- run_setuid_fun(0);
- //此時real uid
= login user id
- //effective uid
= root
- //saved uid
= root
- test_read_file(file);
- getchar();
- printf("\nTEST 4:setuid(0)\n");
- run_setuid_fun(0);
- //此時real uid
= root
- //effective uid
= root
- //saved uid
= root
- test_read_file(file);
- getchar();
- printf("\nTEST 5:setuid(503)\n");
- run_setuid_fun(503);
- //此時real uid
= login user id
- //effective id
= login user id
- //saved uid
= login user id
- test_read_file(file);
- getchar();
- printf("\nTEST 6:setuid(0)\n");
- //read uid
= login user id
- //effective uid
= login user id
- //saved uid
= login user id
- run_setuid_fun(0);
- test_read_file(file);
- return 0;
- }
root_only.txt文件建立:
此時進程沒有有root用戶權限,不能能對root_only.txt進行讀寫操作