全部博文(930)
分类: C/C++
2010-04-17 16:36:09
linux s位 setuid seteuid
还是步步引入把...
[root@kenthy ~]# ls -l /etc/passwd
-rw-r--r--. 1 root root 1982 2010-04-01 07:08 /etc/passwd
大家可以看到/etc/passwd只有root是可写的,哪为什么我们普通用户也可以修改自己的passwd为???
不解....
man下chmod哦有个set user or group ID on execution (s),这个东东是什么呢?
[root@kenthy ~]# ls -l /usr/bin/passwd
-rwsr-xr-x. 1 root root 22648 2009-09-14 20:14 /usr/bin/passwd
咦,passwd有设置s位,那么s位的作用就是当你运行这个程序的时候是你具有这个程序的所有制的权限...
有点不好理解,ok,那么从一个实例开始把.
有的时候我们程序,可能需要root权限来干点什么事情or坏事... 那就是要用这个了....
如下setsid.c
#include
#include
#include
#include
#include
#include
#include
#include
char* file_name = "/root/sbit_test";
char* str = "this is test\n";
void test_read_file()
{
int fd = open(file_name, O_CREAT | O_RDWR | O_APPEND);
if(fd==-1)
{
printf("%s\n", "open error");
return;
}
printf("%s","[OK]: open successful.");
write(fd, str, strlen(str));
close(fd);
}
int main()
{
int old_uid = getuid();
int old_euid = geteuid();
printf("%s\n", "test1");
printf("uid is %d\t euid is %d\n", getuid(), geteuid());
test_read_file();
printf("%s\n\n", "--------------------------");
printf("%s\n", "test2");
if(seteuid(0)==-1)
{
printf("seteuid:%s\n", strerror(errno));
return -1;
}
printf("uid is %d\t euid is %d\n", getuid(), geteuid());
test_read_file();
system("ls /root/");
printf("%s\n\n", "--------------------------");
printf("%s\n", "test3");
if(seteuid(old_euid)==-1)
{
printf("%s\n", strerror(errno));
return -1;
}
if(setuid(0)==-1)
{
printf("setuid:%s\n", strerror(errno));
return -1;
}
printf("uid is %d\t euid is %d\n", getuid(), geteuid());
test_read_file();
system("ls /root/");
printf("%s\n\n", "--------------------------");
printf("%s\n", "test4");
if(setuid(old_uid)==-1)
{
printf("%s\n", strerror(errno));
return -1;
}
printf("uid is %d\t euid is %d\n", getuid(), geteuid());
test_read_file();
printf("%s\n\n", "--------------------------");
return 0;
}
程序如下,普通用户gcc -Wall -o setsid setsid.c
这个时候这个setsid是普通用户的
以root用户执行
chown root:root setsid
chmod 4111 setsid //这里这个4就是设置s位
到这里差不多了,let us go...
再回到普通用户执行
[kenthy@kenthy test]$ ./setsid
test1
uid is 500 euid is 0
[OK]: open successful.--------------------------
test2
uid is 500 euid is 0
ls: cannot open directory /root/: Permission denied
[OK]: open successful.--------------------------
test3
uid is 0 euid is 0
anaconda-ks.cfg install.log nwebmail-0.1.80 txt
develop install.log.syslog nwebmail-0.1.80.tgz urlencode
expat-2.0.1 libiconv-1.13.1 sbit_test urlencode.c
getpinyin libiconv-1.13.1.tar.gz test urlencode.h
getprice mysql test1
iconv mysql_thread test.c
iconv.c mysql_thread.c tmp
[OK]: open successful.--------------------------
test4
uid is 500 euid is 500
open error
--------------------------
大家看到test3居然普通用户kenthy还可以ls /root/了
还有个发现设置s位后,程序的euid本来就是0了...没有
一般我们开发运行,都是偶尔用用root权限,这么个做法也是提高系统安全性把....
今天终于弄清楚这个s位了....