Linux setuid 实践
2015-06-05 14:55
561 查看
Linux setuid 实践
之前接触过setuid,但是没有深入思考,今天读《Unix编程艺术》,觉得瞬间为这种设计所折服,所以总结一下。一般在设计系统时,为了安全,总是试图使用最小权限模型,除非迫不得已需要特权来访问系统,否则不该信任用户代码。Unix中访问控制是基于用户和组的,所以setuid/setgid正是为了给当前进程设置用户/组ID,从而赋予相应的权限。Under Unix, programs that must be run by ordinary users, but must have write access to security-critical system resources, get that access through a feature called the setuid bit. Executable files are the smallest unit of code that can hold a setuid bit; thus, every line of code in a setuid executable must be trusted. (Well-written setuid programs, however, take all necessary privileged actions first and then drop their privileges back to user level for the remainder of their existence.)
Usually a setuid program only needs its privileges for one or a small handful of operations. It is often possible to break up such a program into cooperating processes, a smaller one that needs setuid and a larger one that does not. When we can do this, only the code in the smaller program has to be trusted. It is in significant part because this kind of partitioning and delegation is possible that Unix has a better security track record than its competitors.
–《Unix编程艺术》
读完了APUE之后,决定实践一下。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> // open() #include <errno.h> #include <string.h> // strerror() int main(){ int fd; setuid(0); // become the superuser to open the master file fd = open("/etc/shadow", O_RDONLY); setuid(-1); // give up the privelige if(fd < 0){ printf("open error! %s(errno=%d)\n", strerror(errno), errno); exit(-1); } // do something with fd return 0; }
如果没有setuid root,则会报错!
open error! Operation not permitted(errno=1)
但是仅有setuid root也是不行的,需要将可执行程序设置SID,其实这里也按时了setuid的应用场景,就是把需要特权的指令限制在一定范围,拥有者是root,但是设置了setuid bit之后,其他用户也可以执行。运行效果如下:
系统种这样的程序也有不少:
相关文章推荐
- Linux之crontab定时任务
- [转]20个你不得不知的Linux服务器性能调优技巧
- Linux中THIS_MODULE宏定义详解
- linux复习笔记第一篇 - 可能会很混乱,因为是看之前的笔记粘贴一遍
- Perforce share workspace between linux and windows
- Linux远程挂载目录
- Linux系统使用cp命令报错cp:omitting directory怎么办?
- centOS 7中上网以及网卡的一些设置
- linux 编译安装php选项详解
- linux下C获取系统时间的方法
- Linux查看内存大小和插槽
- Linux操作系统三大应用领域
- linux下mysql函数的详细案列
- linux系统缓存机制
- 给centos5.5安装zabbix agentd的步骤
- linux小积累
- linux下定时访问某个网址
- Linux mysql常用操作命令
- 2- Linux系统入门
- Linux 用dd生成指定大小的文件